Home

principle of operation

 

The principle is simple, a vba macro creates the script, launches it and then retrieves the result. To retrieve the result, you just need to modify the python code so that it creates a text file with the result in the form of a variable name/value pair separated by a tab:

 with open("c:/test/hauteur_resultante.txt", "w") as file: file.write("hauteur_resultante\t" + str(hauteur_resultante) + "\n") 

The created script must be associated with the values of the excel workbook and the result must be automatically retrieved in excel. Now you have a code that works for you, but it says that the hauteur_resultante.txt file is interesting and that the tree structure is the same for the user. On the other hand, the line aire_du_carre = 81 is not useful to the user. As well as: 
 print("rectangle height"+str(hauteur_resultante)) 


The solution I found so that you can test the program in your python environment then integrate it into an Excel tool without having to modify anything, is to add the #delete! comment on the lines to be deleted.
 
def trouver_hauteur(aire):
    # Calculer la longueur du côté du carré (côté = racine carrée de l'aire)
    cote_carre = aire ** 0.5
    # Calculer le périmètre du carré
    perimetre_carre = 4 * cote_carre
    # Calculer la longueur du côté du triangle équilatéral
    cote_triangle = perimetre_carre / 3
    # Calculer la hauteur du rectangle
    hauteur_rectangle = (perimetre_carre - 2 * cote_triangle) / 2
    return hauteur_rectangle
# Exemple d'utilisation
aire_du_carre = 81 #delete!
hauteur_resultante = trouver_hauteur(aire_du_carre)
with open("c:/test/hauteur_resultante.txt", "w") as fichier: #delete!
    fichier.write("hauteur_resultante\t" + str(hauteur_resultante) + "\n")
print("hauteur rectangle "+str(hauteur_resultante)) #delete!

By doing this, you no longer have to initialize variables or name a directory to export the results.
You will use #ouverture_file_resultat! for opening the file and this will override the open statement.
and for example #area_carre! for initialization: a text between a # and a ! which will be used in excel but will remain a simple comment as long as you work on your environment.
The end of the program simply becomes:
 
# Exemple d'utilisation
aire_du_carre = 81 #delete!
#aire_carre!
hauteur_resultante = trouver_hauteur(aire_du_carre)
with open("c:/test/hauteur_resultante.txt", "w") as fichier: #delete!
#ouverture_fichier_resultat!
    fichier.write("hauteur_resultante\t" + str(hauteur_resultante) + "\n")
print("hauteur rectangle "+str(hauteur_resultante)) #delete!

Up

Next