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