我遇到了一个有趣的问题,我可以在 excel 实例中轻松地从 VB 访问 python 代码,如下所述:Calling python script from excel/vba
但是,当我在 Visual Studio 中以一种形式模仿完全相同的代码结构时, pyscript.language = "python" 行会失败。有谁知道是否可以在 VB .Net 中使用 MSScriptControl.ScriptControl 来控制 python,就像在 excel 中一样?这比为我的 python 脚本设置一个 com 对象要容易得多。
示例代码(需要添加microsoft script control 1.0和excel对象库):
Imports Microsoft.Office.Interop
Public Class Form1
Dim WithEvents PyScript As MSScriptControl.ScriptControl
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim xlApp As New Excel.Application
xlApp.Visible = True
Dim xlwbook As Excel.Workbook = xlApp.Workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet)
Dim xlSheet As Excel.Worksheet = CType(xlwbook.Worksheets(1), Excel.Worksheet)
If PyScript Is Nothing Then
PyScript = New MSScriptControl.ScriptControl
PyScript.Language = "python"
PyScript.AddObject("Sheet", xlSheet)
PyScript.AllowUI = True
End If
PyScript.ExecuteStatement("Sheet.cells(1,1).value='Hello'")
End Sub
End Class