如何计算我的VBA脚本的总范围

给我一个excel文件,其中的任务是计算代码中“范围”的总数,范例:范围(“ReComp”)。 主工作表有超过1453个范围,但是我想知道在脚本中实际使用了多less个范围。

我从来没有尝试过使用VBIDE对象,所以这可能会被更有经验的人改进。 无论如何,它应该给你一个好的开始:

Sub test() 'Needs a reference to Microsoft Visual Basic for Applications Extensibility Dim VBProj As VBIDE.VBProject Dim VBComp As VBIDE.VBComponent Dim CodeMod As VBIDE.CodeModule Set VBProj = ThisWorkbook.VBProject Set VBComp = VBProj.VBComponents("Module1") Set CodeMod = VBComp.CodeModule Dim nme As Name Dim lineNo As Long Dim nmeUsed As Boolean Dim numUsed As Long numUsed = 0 For Each nme In ThisWorkbook.Names nmeUsed = False For lineNo = 1 To CodeMod.CountOfLines If InStr(CodeMod.Lines(lineNo, lineNo), "Range(""" & nme.Name & """") > 0 Then nmeUsed = True numUsed = numUsed + 1 Exit For End If Next If nmeUsed Then Debug.Print nme.Name & " used" Else Debug.Print nme.Name & " not used" End If Next 'Used for testing 'MsgBox Range("xxx").Address 'MsgBox Range("yyy").Address MsgBox numUsed & " range names were used out of the " & _ ThisWorkbook.Names.Count & " total" End Sub 

Notepad ++或直接将代码复制到单词中。 然后做一个类似的range(你应该得到一个命中计数