有没有办法自动添加Option Private Module
到VBA中的所有模块?
Option explicit
当我们在Extras> Option>编辑器中标记复选框以声明变量时,会自动添加?
因为通过所有模块并手动编写它似乎是唯一的选择.
子问题:
如果必须添加Option Private Module
10个应用程序中的所有模块,您会做什么?
起初我想使用一个简单的替换并替换Option Explicit
with Option Explicit ^p Option Private Module
,但它也会在类中替换它,我必须从那里删除它.
在这里节省约30分钟的想法?
这应该可以帮助您完成大部分工作,此示例适用于所有未受保护的开放项目.如果您需要修改受保护的项目,请先取消保护.
请记住,您需要明确保存对任何加载项的更改.
有关各种检查背后的基本原理,请参阅内联注释
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