CodeModule.Find 方法更改变量值(查找方法 VBA 加载项对象模型)

CodeModule.Find Method changes value of variables (Find Method VBA Add-In Object Model)

我正在尝试在当前 VBProject 中搜索过程名称的实例。为此,我使用 CodeModule.Find 方法(详细信息 here),它要求:

出于某种原因,每次我调用此方法时,它都会将 st_lineen_line 变量的值更改为不同的数字。在我提供的简单示例中,我似乎不需要多次使用这些数字,但在我的应用程序中我需要,而且方法不断改变它们!

代码:

Sub Find_Method_Changes_Var_Values()

    Dim st_line As Long, en_line As Long
    Dim search_String As String
    Dim VBC As VBIDE.VBComponent

    search_String = "Sub"
    st_line = 5
    en_line = 100
    Set VBC = ThisWorkbook.VBProject.VBComponents("ThisWorkbook")

    ***If VBC.CodeModule.Find(search_String, st_line, 1, en_line, 500) = True Then
        MsgBox "Found our target."
    End If
End Sub

一旦前面三个星号的那一行是运行(不管它是否真的找到了我们要搜索的字符串),st_line和[=19=的值] 都改为 20.

该方法所做的似乎是将 st_lineen_line 变量更改为该方法找到搜索词第一个实例的行。

我怎样才能既使用此方法又保留我的变量值?

来自本主题的文档:

startline Required. A Long specifying the line at which you want to start the search; will be set to the line of the match if one is found. The first line is number 1.

看起来 VBC.CodeModule.Find 正在更改起始线。它同样影响端线:

endline Required. A Long specifying the last line of the match if one is found. The last line may be specified as 1.

您必须使用另一对设置为相同值的变量,因此更改:

st_line = 5
en_line = 100
Set VBC = ThisWorkbook.VBProject.VBComponents("ThisWorkbook")

***If VBC.CodeModule.Find(search_String, st_line, 1, en_line, 500) = True Then
    MsgBox "Found our target."
End If

st_line = 5
en_line = 100
' temporary variables
temp_st_line = st_line
temp_en_line = en_line
Set VBC = ThisWorkbook.VBProject.VBComponents("ThisWorkbook")

***If VBC.CodeModule.Find(search_String, temp_st_line, 1, temp_en_line, 500) = True Then
    MsgBox "Found our target."
End If

来源:https://msdn.microsoft.com/en-us/library/aa443952(v=vs.60).aspx