简体   繁体   中英

VBA equivalent to Excel's “Search()”

I have an assignment I need some help with. There are three columns: Column A(username), Column B(Category), and Column C(note). I have to create a Sub that checks each cell down Column B according to category (for example Admin). If the string, "Admin", is found in B2 for example, then the A2 is searched for either:"john.deer", "BES", or "mars". If "john.deer" is found then C2 is to say "Domain Admin Account", if "BES" is found then C2 is to say "BES Admin Account" etc.

However if "Admin" is not found in Column C then "SQL" is searched in C2. If "SQL" is found then "SQL Server", "SQL Engine", and "SQL Cluster" is searched in A2. The exact same task as the previous paragraph except different strings are searched in Column B and A. Different strings are outputted to Column C as well.

I had an equation that was perfect and just needed to create an equivalent for VBA:

=IF(NOT(ISERROR(SEARCH("admin",B3))),IF(NOT(ISERROR(SEARCH("john.deer",A3))),"Domain Admin Account",if(not(iserror(search("bes",a2))),"BES  Admin Account", if(not(iserror(search("mars",a2))),"Cisco Admin Account","no category"),IF(NOT(ISERROR(SEARCH("SQL",B3))),IF(NOT(ISERROR(SEARCH("sqlserver",A3))),"SQL Server",IF(NOT(ISERROR(SEARCH("sqlengine",B3))),"SQL Engine Account"," ")))

As you can tell its a mess, which is why I wish to create a VBA equivalent. However, there is no Search() object in VBA, only .Find.

Here is my attempt at VBA before realizing Search did not work:

    Private Sub CommandButton21_Click()

If Not IsError Then
    If Search("ADMIN", "B2") Then 'Searches Col. F for "Admin", then Col. B for type of admin before
                                'populating Notes Col. with specific Note

    If Not IsError Then
        Search("john.deer", "A2") = "Domain Admin Account"
    ElseIf Not IsError Then
        Search("BES", "A2") = "BES Admin Account"
    ElseIf Not IsError Then
        Search("mars1", "A2") = "Admin Account for Cisco Phone System"
    Else
  End If

If Search("admin", "B2") Then
    If Not IsError Then
        Search("uccxadmin", "b2") = "Admin Account for Cisco phone system"

End If
end if
end sub

Instr is the VBA eqivalent

dim Pos as long
Pos=Instr(Range("B2"),"ADMIN")
if pos>0 then 'code if found
else 'notfound
end if

Instr has more options than search: see documentation here .

You can use any function available in Excel in your VBA code. You can access this function in Application.WorksheetFunction object: Application.WorksheetFunction.Search . Use the same arguments you would use in the spreadsheet.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM