【问题标题】:I'm trying to adapt the code for when the searched item is not found我正在尝试调整代码以适应未找到搜索项目的情况
【发布时间】:2020-05-07 22:58:47
【问题描述】:

我有这段代码可以在特定工作表上搜索单独的工作簿,并在我搜索的下一个单元格中为我提供数据。如果找到搜索的项目,这很好用,但如果找不到搜索的项目,我似乎无法调整代码。发生这种情况时,我只想向用户表单上的标签返回一条消息,表明找不到该项目。我已经观看并阅读了教程并尝试使用 If Not Is Nothing,但我似乎无法让它发挥作用。 如果有人可以提供帮助,我将不胜感激?非常感谢。

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

【问题讨论】:

  • 您无法返回 Nothing 的值,从您的发现中删除所有 .Value。将foundItem 声明为Range 而不是String 然后您可以在尝试将其分配给标签之前测试If not foundItem is nothing then

标签: excel vba search error-handling


【解决方案1】:

你有没有想过把它写成一个函数?如果该函数返回“某物”,那么这就是您想要的消息。所以它看起来像这样:

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

试试这个。 它可能需要一些编辑才能工作,但想法就在那里。

【讨论】:

    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 2020-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多