【发布时间】:2016-11-22 15:15:46
【问题描述】:
我正在 Excel VBA 中编写一个脚本,该脚本在考虑用户输入条件的国家数据库中运行搜索。搜索超出了UserForm,该UserForm 考虑了来自三个搜索字段的用户搜索。除了“国家”之外,用户还可以通过提及感兴趣的“信息类别”和“信息子类别”来缩小搜索范围。所有这些字段都是链接到列表的ComboBox。类别和子类别的一些示例包括“地理”、“经济指标”、“媒体”、“人口统计”等。
根据用户提供的条件,脚本将返回搜索结果 - 如果与数据库有任何匹配 - 或者,MsgBox 建议搜索未找到匹配项。我想知道MsgBox 中显示的文本是否是固定的,或者它是否可以依赖于用户输入的变量。
为澄清起见,让我们举个例子,一个用户正在寻找有关美国的信息,并在仅填充此条件的情况下运行搜索。该数据库包含有关美国的信息并返回所有可用信息。尽管有所有数据,但用户特别想要有关美国媒体的信息,并使用这两个标准重复搜索。但是,该数据库没有专门关于美国和媒体的信息。在这种情况下,脚本返回一个MsgBox,根据我目前的代码——它工作正常——只是说“数据库没有与此搜索匹配的信息”。
我的问题是:MsgBox 是否可以返回取决于用户搜索的消息,即在示例中返回类似“没有关于美国媒体的信息”之类的内容?非常感谢您的帮助。
这是运行搜索的代码:
country = Sheets("Results").Range("D5").Value
Category = Sheets("Results").Range("D6").Value
Subcategory = Sheets("Results").Range("D7").Value
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
ElseIf Sheets("Database").Cells(i, 1) = country And _
(Sheets("Database").Cells(i, 3) <> Category) Then
MsgBox "The database has no information that matches this search."
Sheets("Results").Range("D5").ClearContents
Sheets("Results").Range("D6").ClearContents
Sheets("Results").Range("D7").ClearContents
Exit Sub
End If
Next i
【问题讨论】:
-
请在发布前提供代码尝试。谢谢
-
我已经提供了我编写的代码。谢谢。