excel - 我正在尝试针对未找到搜索项的代码进行调整

标签 excel vba search error-handling

我有这段代码可以在特定的工作表上搜索单独的工作簿,并在搜索的下一个单元格中提供数据。如果找到了搜索到的项目,这很好用,但是如果没有找到搜索到的项目,我似乎无法适应代码。发生这种情况时,我只想向用户表单上的标签返回一条消息,即未找到该项目。我已经看过并阅读了教程,并尝试使用(如果不是很简单),但我似乎无法使其正常工作。
如果有人可以帮忙,我将不胜感激。非常感谢。

Dim departments As Workbook
Dim searchItem As String
Dim foundItem As String


Set departments = Workbooks.Open("C:\Users\MyPc\Desktop\Department References.xls")

searchItem = UserForm1.Textbox1.Value

If Menu.optionBtnDepartmentOne = True Then
foundItem = departments.Worksheets("Department One").Range("D2:D10000").Find(searchItem).Offset(0, 1).Value

ElseIf Menu.optionBtnDepartmentTwo = True Then
foundItem = departments.Worksheets("Department Two").Range("D2:D10000").Find(searchItem).Offset(0, 1).Value

ElseIf Menu.optionBtnDepartmentThree = True Then
foundItem = departments.Worksheets("Department Three").Range("D2:D10000").Find(searchItem).Offset(0, 1).Value

End If

UserForm1.Label = foundItem
Workbooks("Department References").Close SaveChanges:=False

最佳答案

您有想法将其编写为函数吗?而且,如果函数返回“something”,那么就会出现您想要的消息。所以它看起来像这样:

Sub fill_UF()

Dim searchItem as string

SearchItem = UserForm1.Textbox1.Value

If foundItem(searchItem)= "Did not Find item" then 
Msgbox foundItem(searchItem)
goto ending
End if

UserForm1.Label = foundItem(searchItem)

ending:
End sub

'
Function foundItem(searchItem as string)

Dim departments As Workbook
'Dim searchItem As String
'Dim foundItem As String


Set departments = Workbooks.Open("C:\Users\MyPc\Desktop\Department References.xls")

'searchItem = Cstr(searchItem) ' sometimes you need to add this

If Menu.optionBtnDepartmentOne = True Then
foundItem = departments.Worksheets("Department One").Range("D2:D10000").Find(searchItem).Offset(0, 1).Value
Goto ending

ElseIf Menu.optionBtnDepartmentTwo = True Then
foundItem = departments.Worksheets("Department Two").Range("D2:D10000").Find(searchItem).Offset(0, 1).Value
Goto ending

ElseIf Menu.optionBtnDepartmentThree = True Then
foundItem = departments.Worksheets("Department Three").Range("D2:D10000").Find(searchItem).Offset(0, 1).Value
Goto ending
End If

foundItem = "Did not Find item"

ending:
Workbooks("Department References").Close SaveChanges:=False

End function

尝试这个。
它可能需要进行一些编辑才能起作用,但是这个想法就在那里。

关于excel - 我正在尝试针对未找到搜索项的代码进行调整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61669195/

相关文章:

excel - 如何按月份名称过滤excel列?

excel - 使用 Excel VBA 将行从一个列表对象复制到另一个

PHP 搜索 MySQL 数据库错误

css - 搜索栏的定位

excel - 创建一个复选框,复制它,然后将新的复选框报告到新位置

VBA - 使用 Dim 值获取范围 - 对象 __global 的范围失败

excel - 如何使用行输入搜索字符串,然后在 Excel 单元格中打印接下来的 5 行

如果设计表链接到零件文件(从 Excel 控制),则 VBA SOLIDWORKS Pack and Go 重命名不起作用

excel - 从工作表调用的 Excel VBA UDF 是否可以传递除 'Range' 以外的任何 Excel VBA 对象模型类的实例?

algorithm - A*算法重新打开顶点