使用Excel 2010。
我需要将代码添加到已重命名ThisWorkbook模块的远程Excel文件中,让我们对“#DashboardWorkbook"”说。我不知道新名称,除了我需要以编程方式识别此模块,以便向Sub Workbook_Open()添加更多代码。
我打开这个远程文件,然后我浏览了它的所有组件:
Private Sub AddProcedureToWorkbook(wb As Workbook)
Dim VBProj As VBIDE.VBProject
Dim oComp As VBIDE.VBComponent
Dim oCodeMod As VBIDE.CodeModule
Set VBProj = wb.VBProject
For Each oComp In VBProj.VBComponents
If *[check here if oComp was formerly ThisWorkbook but now renamed]* Then
Set oCodeMod = oComp.CodeModule
'add new code here
...etc, etc
End If
Next
End Sub
在Excel界面中,ThisWorkbook有一个不同的图标,所以它似乎是一个不同的模块类型,但我无法弄清楚要识别它的具体属性是什么?
为了使事情复杂化,有时Sub Workbook_Open()不存在,因此我需要将它添加到正确的位置......
谢谢,
M.R。
答案 0 :(得分:5)
可以通过CodeName
直接从代码访问表格和书籍(不同于显示名称,只有Name
)。
这也是他们的VBComponent名称。
Private Sub AddProcedureToWorkbook(wb As Workbook)
Dim VBProj As VBIDE.VBProject
Dim oComp As VBIDE.VBComponent
Dim oCodeMod As VBIDE.CodeModule
Set VBProj = wb.VBProject
Set oComp = VBProj.VBComponents(wb.CodeName)
Set oCodeMod = oComp.CodeModule
oCodeMod.AddFromString "sub Hi()" & vbNewLine & "msgbox ""Hi.""" & vbNewLine & "end sub"
End Sub
答案 1 :(得分:2)
每个VBProj.VBComponents
项都有Properties
个集合。 Workbook对象的属性集与其他对象(表格,模块等)不同。
选择工作簿的唯一属性并搜索组件集合。
试试这个
Private Function FindThisWorkbook(wb As Workbook) As VBIDE.VBComponent
Dim VBProj As VBIDE.VBProject
Dim oComp As VBIDE.VBComponent
Dim oP As Property
Set VBProj = wb.VBProject
For Each oComp In VBProj.VBComponents
Set oP = Nothing
On Error Resume Next
Set oP = oComp.Properties("ActiveSheet")
On Error GoTo 0
If Not oP Is Nothing Then
' Found it
Set FindThisWorkbook = oComp
Exit Function
End If
Next
End Function