2

I have been using a piece of code to find specific text within vba modules.

It works well for finding a single line (or less) of text. So, for example it will find 'mySub' in a module with text :

Private sub mySub() 
  Dim a as Integer  
  Dim b as Integer  
End Sub

The code I am using:

Set m = myAp.Modules(name)
m.find(text_find, 1, 1, -1, -1, False, False, False)

The problem begins when I want to search for multi-line texts. For example I want to find the section of text:

Dim a as Integer
Dim b as Integer

Unfortunately the find function is returning a false when I try presenting my multi-line search text.

Using debug (watch/immediate) I confirmed that my search criteria (text_find) does contain chrs 13 + 10 in between the first 'Integer' and the 'Dim b'.

I also examined the module.Line value for the "Dim a" line, and that also ends with chrs 13 + 10.

So now I am really struggling to know how to get this working.

If anyone has any help on this - would be appreciated.

Thanks

ThunderFrame
  • 9,352
  • 2
  • 29
  • 60
Esby
  • 105
  • 1
  • 15
  • Interesting. I can't get this to work too. `.Find("Dim a as Integer*Dim b as Integer", y1, x1, y2, x2, PatternSearch:=True)` doesn't work either. It may be impossible - but then the `EndLine` parameter would be sort of pointless. – Andre Nov 01 '15 at 08:22
  • Did you use instr instead of find keyword to search a word ? – PASUMPON V N Nov 01 '15 at 10:32

1 Answers1

2

You can't search across more than one line of code using the Find method, but you can read all of the lines into a string, and then use InStr to locate each occurrence of the search terms:

Option Compare Database

Dim a As Integer
Dim b As Integer

Sub test()

  Const search As String = "Dim a As Integer" & vbCrLf & "Dim b As Integer"

  Dim md As Module
  Set md = Modules("Module1")

  Dim allLines As String
  allLines = md.Lines(1, md.CountOfLines)

  'Get the first instance of the search term...
  Dim pos As Long
  pos = InStr(1, allLines, search, vbTextCompare)

  Dim found As Boolean
  found = pos > 0

End Sub

You should note however, that parsing VBA with Find or InStr is going to be next to impossible. You need a state machine to do it reliably, or you need a library like ANTLR.

Consider a module that contains:

Dim a      As Integer 'some comment _
some comment
Dim b _
  As _
  Integer 'Some other comment

How do you write a search term that can handle that???

FYI - The Rubberduck VBA project (to which I contribute) has been refining a VBA grammar that can parse nearly all VBA syntax.

ThunderFrame
  • 9,352
  • 2
  • 29
  • 60