更新时间:2023-01-19 19:30:31
我已将此代码放在Excel中的"ThisWorkbook"对象中:
I've put this code in the "ThisWorkbook" object in Excel:
Public Sub TestScript()
Debug.Print "Hello"
End Sub
,然后使用窗体上的按钮从Access中成功调用它:
And then successfully called it from Access using a button on a form:
Private Sub cmdRunExcel_Click()
Dim xl As Excel.Application
Set xl = CreateObject("Excel.Application")
xl.Visible = True
xl.Workbooks.Open "C:/Your/FolderPath/And/FileName.xlsx", True, False
xl.Run "ThisWorkbook.TestScript"
Set xl = Nothing
End Sub
诚然,我没有给它很多运行的代码,但是这里的代码至少是在Excel上运行的,来自Excel ...这一定比尝试在上面运行代码更好.通过Access获得Excel.
Admittedly I've not given it a lot of code to run, but here the code is at least running on Excel, from Excel... which must be better than trying to run code on Excel from Access.
更新:查看是否可以通过对此进行测试来从Access to Excel创建模块(由于使用的是工作计算机,所以我无法对其进行正确的测试,并且似乎不允许我这样做)由于安全设置而运行这种类型的代码)
Update: See if you can create the module from Access to Excel by testing this (I can't test it properly because I'm using a work computer and it seems to be not letting me run this type of code due to security settings)
Private Sub cmdRunExcel_Click()
Dim xl As Excel.Application
Dim myWrkBk As Excel.Workbook
Dim myModule As VBComponent
Dim strVb As String
Set xl = CreateObject("Excel.Application")
xl.Visible = True
xl.Workbooks.Open "C:/Your/FolderPath/And/FileName.xlsx", True, False
Set myWrkBk = xl.Workbooks.Add
Set myModule = myWrkBk.VBProject.VBComponents.Add(vbext_ct_StdModule)
strVb = "Public Sub TestScript()" & vbCrLf _
& "Debug.Print 'Hello'" _
& "End Sub"
myModule.CodeModule.AddFromString strVb
' xl.Run "ThisWorkbook.TestScript"
Set myModule = Nothing
Set myWrkBk = Nothing
Set xl = Nothing
End Sub