在VBA代码中搜索文本(在哪一行)

时间:2015-06-03 08:30:35

标签: excel vba search line

我想知道如何搜索VBA模块中的每一行并获取找到文本的任何行的编号。我发现了这样的事情:

Sub addProcedure()

Dim vbProj As VBIDE.VBProject
Dim vbComp As VBIDE.VBComponent
Dim vbCode As VBIDE.CodeModule

Dim strSearchPhrase As String
Dim strModuleName As String
Dim intLinesNr As Integer
Dim i As Integer
Dim intFoundLine As Integer

strModuleName = "Test"

Set vbProj = ActiveWorkbook.VBProject
Set vbComp = vbProj.VBComponents(strModuleName)
Set vbCode = vbComp.CodeModule

intLinesNr = vbCode.CountOfLines


For i = 1 To intLinesNr
  If vbCode.Find(strSearchPhrase, i, 1, -1, -1) Then
    intFoundLine = i
    Exit For
  End If
Next i

If foundline <> 0 Then MsgBox "Text found in " & intFoundLine & " line."


Set vbComp = Nothing
Set vbProj = Nothing
Set vbCode = Nothing
End Sub

它返回编译错误:ByRef参数类型不匹配:

If vbCode.Find(strSearchPhrase, i, 1, -1, -1) Then

其他任何想法如何做到这一点?

1 个答案:

答案 0 :(得分:2)

Dim i As Integer更改为Dim i As Long可能会解决不匹配错误吗?

  

CodeModule对象有一个Find方法,可用于在代码模块中搜索文本。 Find方法接受ByRef Long参数。

来源 - &gt; http://www.cpearson.com/excel/vbe.aspx