我在Excel VBA中编写了一个脚本,该脚本在考虑用户输入的条件的情况下在国家/地区数据库中运行搜索。搜索用完了,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
您掌控MsgBox
一切,因此您所要做的就是正确处理逻辑以相应地更改消息。
一种非常简单的方法是简单地更改以下行:
MsgBox "The database has no information that matches this search."
就像您提到的那样,使用变量中的值:
MsgBox "There is no information regarding " & Category & " in the " & country & "."
假设在搜索时Category
包含“媒体”并且country
包含“美国”,这将输出“在美国没有有关媒体的信息”。如您所料。
如果要根据用户输入的确切值来为消息使用不同的模式,则必须使用更多的模式If...Then...Else
来正确处理它们。在这里,我只是使用一个设置短语并使用参数更改硬编码值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句