我正在尝试更改我的加载项,以便在打开新工作簿时打开新工作表,然后在新工作表中创建新的事件过程。
我已经达到了可以使用宏按钮组合“Sheets.Add”和“.CreateEventProc”的程度,但是当尝试使用加载项工作簿来解决问题时自动化过程。加载项首先加载,因此“Set VBProj = ActiveWorkbook.VBProject”找不到新的活动工作簿。
有可能这样做吗?如果是这样,是否需要解决问题,或者我只是遗漏了一些明显的东西?
这就是我现在所拥有的:
Option Explicit
Private WithEvents App As Excel.Application
Private Sub Workbook_Open()
Set App = Excel.Application
End Sub
Private Sub App_NewWorkbook(ByVal Wb As Workbook)
Range("T2").Value = 100
ActiveWorkbook.Sheets.Add
Call CreateEventProcedure
End Sub
Public Sub CreateEventProcedure()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim NumLines As Long
Dim LineNum As Long
Dim ProcName As String
Dim ProcKind As VBIDE.vbext_ProcKind
Const DQUOTE = """" ' one " character
Set VBProj = ActiveWorkbook.VBProject
Set VBComp = VBProj.VBComponents("Sheet2")
Set CodeMod = VBComp.CodeModule
With CodeMod
LineNum = .CountOfDeclarationLines + 1
Do Until LineNum >= .CountOfLines Or ProcName = "Worksheet_Change"
ProcName = .ProcOfLine(LineNum, ProcKind)
LineNum = .ProcStartLine(ProcName, ProcKind) + _
.ProcCountLines(ProcName, ProcKind) + 1
Loop
If ProcName = "Worksheet_Change"
GoTo Exi
End If
'Now, create a Change Event on Sheet2
LineNum = .CreateEventProc("Change", "Worksheet")
答案 0 :(得分:0)
对于那些关心的人,我让这个过程处理了一个轻微的并发症。这是我做的:
Option Explicit
Private WithEvents ExApp As Excel.Application
Public Sub ExApp_WorkbookOpen(ByVal Wb As Workbook)
Dim StrPrompt As String
Dim strTitle As String
Dim iRet As Integer
StrPrompt = "Want to create event?"
strTitle = "Event?"
On Error GoTo 0
iRet = MsgBox(StrPrompt, vbYesNo, strTitle)
If iRet = vbYes Then
ActiveWorkbook.Sheets.Add
Call CreateEventProcedure
End If
On Error GoTo 0
ActiveWorkbook.Sheets.Add
Call CreateEventProcedure
End If
End Sub
Private Sub Workbook_Open()
Set ExApp = Excel.Application
End Sub
我创建了Yes / No提示绕过第一个'run-time _Global'错误然后excel工作簿实际加载,提示再次问我然后我点击是,一切正常。此外,当在excel中打开工作簿时,这只需要一个提示。