VBA in Excel to search for string over multiple tabs and return locations -
i have formed code searching problem trying find multiple results. return first location of string on each tab moves on. when implement while loop commented out appears find first result , escape loop.
i'm not sure if there quirk vba loops missing or while check not quite right have tried debug breaking down , using message boxes no avail besides narrowing believe issue in while loop code.
public function getsearcharray(strsearch string) string dim strresults string dim sht worksheet dim rfnd range dim sfirstaddress range each sht in thisworkbook.worksheets 'msgbox "looping on worksheets" set rfnd = nothing sht.usedrange 'msgbox "searching for" & strsearch set rfnd = .cells.find(what:="*" & strsearch & "*", lookin:=xlvalues, lookat:=xlpart, searchorder:=xlrows, searchdirection:=xlnext, matchcase:=false) if not rfnd nothing 'save first result can exit loop if sfirstaddress nothing msgbox "we have result , sfirstaddress nothing" set sfirstaddress = rfnd end if 'need loop within sheet keep finding results 'while (not rfnd nothing) , rfnd <> sfirstaddress 'deal results , build string if strresults = "" 'msgbox "no prev results" strresults = "worksheet(" & sht.index & ").range(" & chr(34) & rfnd.address & chr(34) & ")" msgbox "first result " & strresults else strresults = strresults & "|" & "worksheet(" & sht.index & ").range(" & chr(34) & rfnd.address & chr(34) & ")" msgbox strresults end if set rfnd = .findnext(rfnd) 'wend end if end msgbox "end sheet loop.." next msgbox "finished going on sheets" msgbox strresults end function
something should work you:
public function getsearcharray(strsearch string) string dim ws worksheet dim rngfound range dim strfirst string dim strwsname string each ws in activeworkbook.sheets set rngfound = ws.usedrange.find(strsearch, ws.usedrange.cells(ws.usedrange.cells.count), xlvalues, xlpart) if not rngfound nothing strwsname = ws.name if instr(1, ws.name, " ", vbtextcompare) > 0 strwsname = "'" & strwsname & "'" strfirst = rngfound.address getsearcharray = getsearcharray & "|" & strwsname & "!" & rngfound.address set rngfound = ws.usedrange.find(strsearch, rngfound, xlvalues, xlpart) loop while rngfound.address <> strfirst end if next ws if len(getsearcharray) > 0 getsearcharray = mid(getsearcharray, 2) end function
then call function, use this:
sub tgr() msgbox replace(getsearcharray("test"), "|", chr(10)) end sub
Comments
Post a Comment