在Excel VBA中查找和如果语句

我正在尝试编写一个脚本,通过位于名为“数据库”的工作表中的Excel数据库执行search。 search结果将被呈现在名为“结果”的表格中。 可以根据用户input的一定标准进行search,即“国家”,“类别”和“子类别”。 这些被定义为依赖于用户的variables,如下所示:

country = Sheets("Results").Range("D5").Value Category = Sheets("Results").Range("D6").Value Subcategory = Sheets("Results").Range("D7").Value 

我希望强制填写“国家/地区”字段,以便进行search。 如果此条件得到validation,则search将根据用户提供的其余条件运行。 为了实现这一点,我写了以下内容:

 finalrow = Sheets("Database").Range("A200000").End(xlUp).Row For i = 2 To finalrow 'If the country field is left empty If country = "" Then Sheets("Results").Range("B10:J200000").Clear MsgBox "You must select a country in order to search the database. Please do so in the drop-down list provided." Sheets("Results").Range("D5").ClearContents Sheets("Results").Range("D6").ClearContents Sheets("Results").Range("D7").ClearContents Exit Sub 'If the country field is filled in and there results from the search made ElseIf Sheets("Database").Cells(i, 1) = country And _ (Sheets("Database").Cells(i, 3) = Category Or Category = "") And _ (Sheets("Database").Cells(i, 4) = Subcategory Or Subcategory = "") Then 'Copy the headers of the table With Sheets("Database") .Range("A1:I1").Copy End With Sheets("Results").Range("B10:J10").PasteSpecial 'Copy the rows of the table that match the search query With Sheets("Database") .Range(.Cells(i, 1), .Cells(i, 9)).Copy End With Sheets("Results").Range("B20000").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats 'Hides search form Me.Hide End If 

像这样,脚本和search运行良好。

我现在要考虑用户填写“国家”字段的事件,但input的值与数据库中的任何内容都不匹配,即数据库不包含有关所search国家的信息。 我被build议通过在已经写好的If statement语句之前插入一个.Find语句来执行此操作,以便脚本检查,首先,如果国家在数据库中并且只有在继续search之后。 作为编码的初学者,我在网上search,这就是我最终写的:

 With Worksheets("Database") Set c = Range("A:A").Find(What:=country, After:=.Cells(1, 1), _ LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByRows, _ SearchDirection:=xlNext, MatchCase:=False) If Not c Is Nothing Then MsgBox "Unfortunately, the database does not have any information regarding the country you specified. Please search for information on another country." Exit Sub End If End With 

这不起作用。 无论何时我在数据库中input一个国家,脚本仍会显示结果。 但是,只要我将“国家/地区”字段留空,它就会停止返回MsgBox "You must select a country in order to search the database. Please do so in the drop-down list provided." 每当我input一个不存在的国家,它只是呈现“结果”表没有结果。

我该如何解决这个问题? 非常感谢您的帮助。