是否有办法自动将Option Private Module
添加到VBA中的所有模块?
当我们在Extras> Option>编辑器中标记复选框以声明变量时,会自动添加Option explicit
吗?
因为浏览所有模块并以某种方式手动编写它似乎是唯一的选择。
子问题:
如果你必须将Option Private Module
添加到10个应用程序中的所有模块,你会做什么?
起初我想使用简单的替换并将Option Explicit
替换为Option Explicit ^p Option Private Module
,但它也会在类中替换它,我必须从那里删除它。
想在这里节省30分钟?
答案 0 :(得分:9)
这应该可以帮助您完成大部分工作,此示例适用于所有未受保护的开放项目。如果您需要修改受保护的项目,请先取消保护它们。
请记住,您需要明确保存对任何加载项的更改。
请参阅内联评论,了解各种检查背后的理由
Sub Foo()
'Add a reference to Visual Basic for Applications Extensibility
Dim proj As VBIDE.VBProject
Dim comp As VBIDE.VBComponent
For Each proj In Application.VBE.VBProjects
'Check the project isn't protected
If proj.Protection = vbext_pp_none Then
For Each comp In proj.VBComponents
'Check we're working with a standard module
If comp.Type = vbext_ct_StdModule Then
'TODO: Check that Option Private Module doesn't already exist
comp.CodeModule.InsertLines 1, "Option Private Module"
End If
Next comp
End If
Next proj
End Sub
从OP编辑(@vityata): 我已经决定将你的更新添加到你的答案中(我希望你不介意)。这是后期绑定,因此不需要库:
'---------------------------------------------------------------------------------------
' Method : AddOptionPrivate
' Author : stackoverflow.com
' Date : 12.01.2017
' Purpose: Checking for "Option Private Mod~" up to line 5, if not found we add it in
' every module
'---------------------------------------------------------------------------------------
Sub AddOptionPrivate()
Const UP_TO_LINE = 5
Const PRIVATE_MODULE = "Option Private Module"
Dim objXL As Object
Dim objPro As Object
Dim objComp As Variant
Dim strText As String
Set objXL = GetObject(, "Excel.Application")
Set objPro = objXL.ActiveWorkbook.VBProject
For Each objComp In objPro.VBComponents
If objComp.Type = 1 Then
strText = objComp.CodeModule.Lines(1, UP_TO_LINE)
If InStr(1, strText, PRIVATE_MODULE) = 0 Then
objComp.CodeModule.InsertLines 2, PRIVATE_MODULE
End If
End If
Next objComp
End Sub
答案 1 :(得分:3)
我花了一点时间来修改我的exisitng代码,你可以尝试下面的代码来重新定位" Option Explicit"使用"选项专用模块"。
<强>代码强>
Option Explicit
Sub ReplaceOptionExplicitInModules()
Dim VBProj As VBIDE.VBProject
Dim VBComp As VBIDE.VBComponent
Dim CodeMod As VBIDE.CodeModule
Dim i As Long
' loop though all open projects
For Each VBProj In Application.VBE.VBProjects
If VBProj.Protection = vbext_pp_none Then
' loop through all modules, worksheets and other objects in VB Project
For Each VBComp In VBProj.VBComponents
If VBComp.Type <> vbext_ct_ClassModule Then ' <-- check if module type is not class (to replace also on sheet and workbook events)
Set CodeMod = VBComp.CodeModule
' loop through all code lines inside current module
For i = 1 To CodeMod.CountOfLines
If Len(CodeMod.Lines(i, 1)) > 0 Then
' if line contents is "Option Explicit*"
If CodeMod.Lines(i, 1) Like "Option Explicit*" Then
CodeMod.ReplaceLine i, "Option Private Module"
End If
End If
Next i
End If
Next VBComp
End If
Next VBProj
End Sub