VBA相当于Excel的“search()”

我有一个任务,我需要一些帮助。 有三列:列A(用户名),列B(类别)和列C(注)。 我必须创build一个Sub,根据类别(例如Admin)检查列B下的每个单元格。 如果在B2中findstring“Admin”,则searchA2:“john.deer”,“BES”或“mars”。 如果find“john.deer”,那么C2就是说“Domain Admin Account”,如果find“BES”,那么C2就是说“BES Admin Account”等

但是,如果在列C中找不到“Admin”,则在C2中search“SQL”。 如果find“SQL”,则在A2中search“SQL Server”,“SQL Engine”和“SQL Cluster”。 在B列和A列中search除了不同string以外的完全相同的任务。不同的string也输出到C列。

我有一个完美的方程,只需要创build一个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"," "))) 

你可以把它弄得一塌糊涂,这就是为什么我想创build一个VBA等价物。 但是,VBA中没有Search()对象,只有.Find。

这是我在尝试VBA之前实现search没有工作:

  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是VBA等价性

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

Instr比search有更多select:请参阅文档。

您可以在VBA代码中使用Excel中可用的任何函数。 你可以在Application.WorksheetFunction对象中访问这个函数: Application.WorksheetFunction.Search 。 使用您在电子表格中使用的相同参数。