删除模块Excel VBA时运行时错误“9”

我正与几位同事共享一个工作表。 这个电子表格最终将被发送到外部的一方,所以我们作为macros的一部分以编程方式移除VBE模块。 我使用了这个来自微软文档的代码:

Dim vbCom As Object Set vbCom = Application.VBE.ActiveVBProject.VBComponents vbCom.Remove VBComponent:= vbCom.Item("sample_module") 

它适用于某些用户,但与其他用户发生运行时错误“9”。 脚本的其余部分最终执行,但模块不会被删除。

尝试运行下面的For Each vbCom In .VBComponents循环中的代码,看看你得到了什么:

 Option Explicit Sub CheckVBProjComp() Dim vbCom As Object Dim flag As Boolean Dim VbComName As String VbComName = "sample_module" With ThisWorkbook.VBProject For Each vbCom In .VBComponents If vbCom.Name Like VbComName Then .VBComponents.Remove .VBComponents(vbCom.Name) flag = True Exit For End If Next vbCom End With If flag Then MsgBox "VB Component " & Chr(34) & VbComName & Chr(34) & " successfully removed", vbOKOnly Else MsgBox "Unable to find VB Component " & Chr(34) & VbComName & Chr(34), vbInformation End If End Sub 

您需要添加对VBA扩展性库的引用,并在运行这些命令的每个客户端上启用“信任访问Visual Basic项目”。 您可以从Chip上看到这个页面,其详细信息如下: http : //www.cpearson.com/excel/vbe.aspx

如果目标仅仅是删除给定的Excel工作簿中的所有模块,那么请closures该WorkbookVBProject ,不要认为VBE.ActiveVBProject将成为您所针对的工作簿背后的项目。

此过程将从指定target去除所有非文档模块:

 Public Sub RemoveAllMacros(ByVal target As Workbook) 'if the target is ThisWorkbook, we're removing the very macro we're running! If target Is ThisWorkbook Then Exit Sub Dim components As VBComponents Set components = target.VBProject.VBComponents Dim component As VBComponent For Each component In components If component.Type <> vbext_ct_Document Then components.Remove component Next End Sub