Start the command prompt with the code below and You can run Python.
Dim suji1 As String
Dim suji2 As String
Dim WSH
Dim wExec
Dim cmd_str As String
suji1 = Range("D4").Value ''Get numbers from cells
suji2 = Range("D5").Value
Set WSH = CreateObject("WScript.Shell")
py_file = ThisWorkbook.Path & "\Python.py"
cmd_str = "python " & py_file & " " & suji1 & " " & suji2
cmd_str = Replace(cmd_str, "\", "/")
Set wExec = WSH.Exec("%ComSpec% /c " & cmd_str)
Do While wExec.Status = 0
DoEvents
Loop
Range("D6").Value = Val(wExec.StdOut.ReadAll) ''Receive results from Python
Set wExec = Nothing
Set WSH = Nothing
''Object creation
Set WSH = CreateObject("WScript.Shell")
''Python file path to run
py_file = ThisWorkbook.Path & "\Python.py"
''Command creation
cmd_str = "python " & py_file & " " & suji1 & " " & suji2
cmd_str = Replace(cmd_str, "\", "/")
''Command execution
Set wExec = WSH.Exec("%ComSpec% /c " & cmd_str)
With this, you can easily start the command prompt and You can start Python.
''Command creation
cmd_str = "python " & py_file & " " & suji1 & " " & suji2
suji1 and suji2 are arguments. So you can get the value from the cell etc. and pass it.
If you enter any value in number 1 and number 2, it will be calculated and output to the answer.
By the way, Python is such a code.
import sys
def sum(suji1, suji2):
return suji1 + suji2
if __name__ == "__main__":
argv = sys.argv
suji1 = str(argv[1])
suji2 = str(argv[2])
total = sum(suji1, suji2)
print(total)
When executed, it looks like this.
This time I started Python with VBA, but since I am actually running it using the command prompt I feel that I can do more if I apply it. Also, I will update it if I learn.
Recommended Posts