使用.DeleteLines从模块VBA中删除特定的代码

我想在VBA中使用.DeleteLines函数。 由于我没有删除模块中的所有行,我需要一个有针对性的方法。 我假设有一个像Find(“FooBar”)函数。LineNumber,但是我无法find它在这里/与谷歌:

https://msdn.microsoft.com/en-us/library/office/gg264546.aspx

 Sub Deletings() With Workbooks("ClassExperiment.xlsm").VBProject.VBComponents("Module2").CodeModule .DeleteLines(HowDoIGetThisValue, 0) End With End Sub 

帮助赞赏。

如果要删除整个过程,可以使用ProcStartLine属性find它的位置,使用ProcCountLines查找它的行数。

 Dim module As CodeModule Set module = Workbooks("ClassExperiment.xlsm").VBProject.VBComponents("Module2").CodeModule Dim start As Long Dim lines As Long With module start = .ProcStartLine("button_Click", vbext_pk_Proc) lines = .ProcCountLines("button_Click", vbext_pk_Proc) .DeleteLines start, lines End With 

警告:

这应该是显而易见的,但是我仍然会把它扔出去。 不要使用这个(或任何其他方法)在Debug模式下修改代码运行的模块。 这是打破工作簿的好方法。

 Sub test() Dim vb As VBComponent Dim i As Integer Set vb = ThisWorkbook.VBProject.VBComponents("Module2") For i =vb.CodeModule.CountOfLines to 1 step -1 If InStr(1, vb.CodeModule.Lines(i, 1), "' remove") <> 0 Then vb.CodeModule.DeleteLines i, 1 End If Next i End Sub 

我还build议使用条件语句来允许执行代码行,而不是删除它,何时放回? 这可能会导致问题,如果你想自动化这一点,因为你需要知道它来自哪里。