【问题标题】:Searching for the text in VBA code (in which line)在 VBA 代码中搜索文本(在哪一行)
【发布时间】:2015-06-03 08:30:34
【问题描述】:

我想知道如何在 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

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

【问题讨论】:

  • strSearchPhrase 中有什么内容?这套在哪里?如果您产生错误,然后在即时窗口中键入“?strSearchPhrase”会显示什么?
  • 忘记放到模块里了,strSearchPhrase只是一个文本,我要找的,所以可以是:strSearchPhrase = "Test string"

标签: excel vba search line


【解决方案1】:

也许将Dim i As Integer 更改为Dim i As Long 将解决不匹配错误?

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

来源 -> http://www.cpearson.com/excel/vbe.aspx

【讨论】:

    猜你喜欢
    • 2021-12-21
    • 2012-04-24
    • 2016-11-14
    • 1970-01-01
    • 2021-02-03
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 2012-08-12
    相关资源
    最近更新 更多