VBA equivalent to Excel's “Search()”

拈花ヽ惹草 提交于 2020-01-17 06:36:41

问题


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

回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/32618087/vba-equivalent-to-excels-search

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!