我试图简单地将测试宏导入我当前的 Excel 工作簿。然后运行宏。我在 Excel 2007 上。我收到错误:
运行时错误“1004”:
无法运行宏“DoKbTest”。该工作簿中的宏可能不可用,或者所有宏都可能被禁用。
如果我将一行代码更改为:Set oBook = oExcel.Workbooks.Add
它工作正常。为什么当我引用 ThisWorkbook 时它会失败?
这是代码:
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Dim oXL As Excel.Application
Dim oBook As Excel.Workbook
Dim oSheet As Excel.Worksheet
Dim i As Integer, j As Integer
Dim sMsg As String
' Create a new instance of Excel and make it visible.
Set oXL = GetObject(, "Excel.Application")
oXL.Visible = True
' Add a new workbook and set a reference to Sheet1.
Set oBook = ThisWorkbook
oBook.Activate
Set oSheet = Sheets("Overview")
oSheet.Activate
sMsg = "Fill the sheet from in-process"
MsgBox sMsg, vbInformation Or vbMsgBoxSetForeground
' The Import method lets you add modules to VBA at
' run time. Change the file path to match the location
' of the text file you created in step 3.
oXL.VBE.ActiveVBProject.VBComponents.Import "C:\Users\jstockdale\Desktop\KbTest.bas"
' Now run the macro, passing oSheet as the first parameter
oXL.Run "DoKbTest", oSheet
' You're done with the second test
MsgBox "Done.", vbMsgBoxSetForeground
' Turn instance of Excel over to end user and release
' any outstanding object references.
oXL.UserControl = True
Set oSheet = Nothing
Set oBook = Nothing
Set oXL = Nothing
End Sub
和 .bas 文件
Attribute VB_Name = "KbTest"
' Your Microsoft Visual Basic for Applications macro function takes 1
' parameter, the sheet object that you are going to fill.
Public Sub DoKbTest(oSheetToFill As Object)
Dim i As Integer, j As Integer
Dim sMsg As String
For i = 1 To 100
For j = 1 To 10
sMsg = "Cell(" & Str(i) & "," & Str(j) & ")"
oSheetToFill.Cells(i, j).Value = sMsg
Next j
Next i
End Sub