【问题标题】:Using an input box and msg box to search for data in excel VBA使用输入框和消息框在excel VBA中搜索数据
【发布时间】:2021-07-22 08:11:21
【问题描述】:

我正在开发一个要求我制作的 sub,以便用户可以使用输入框搜索他们的 ProductID,然后使用 msgbox 让他们知道是否找到了它,但我不能获取正确的代码。我在这里做错了什么?完全丢失(代码如下):

Sub test()

    Dim Worksheet As Range
    Dim ProductID As Variant

    ProductID = InputBox("Please enter the Product ID")

    With Worksheets(1).Range("A1:Z1000")
        Set ProductID = .Find("ProductID", LookIn:=xlWhole)

        If found Then
            MsgBox ProductID("was Found")
        Else
            MsgBox ProductID & (" was NOT Found")
        End If

    End With
End Sub

【问题讨论】:

  • Dim found As Range, Set found = .Find(ProductID, LookIn:=xlWhole), If Not found Is Nothing Then, MsgBox ProductId & "was Found", Else, MsgBox ProductID & " was NOT Found"
  • 大本,非常感谢!当我尝试这个时,它会显示“无效或不合格的参考”并突出显示 .Find。
  • Sub test() Dim found As Range Set found = .Find(ProductID, LookIn:=xlWhole) If Not found Is Nothing Then MsgBox ProductID & "was Found" Else MsgBox ProductID & " was NOT Found " 结束子
  • 你需要With Worksheets(1).Range("A1:Z1000"),然后是End IfEnd With
  • 如果我想引用整个工作表而不是 A1:Z1000,我该怎么做?

标签: excel vba search inputbox msgbox


【解决方案1】:

几个问题,包括:

  • Find 的结果分配给Range 变量(与ProductId 分开),例如变量found
  • 使用If Not 表示变量Is Nothing 来测试查找是否成功。
  • 删除Dim Worksheet As Range
  • 变量不属于引号内。 ProductID(不带引号)是变量。 "ProductID" 是文本“ProductID”。使用变量而不是文本调用 Find
  • 应该是LookIn:=xlValuesLookIn:=xlFormulas,然后是LookAt:=xlWhole
Sub test()

    Dim ProductID As Variant
    ProductID = InputBox("Please enter the Product ID")

    Dim found As Range
    Set found = Worksheets(1).Cells.Find(What:=ProductID, LookIn:=xlValues, LookAt:=xlWhole)

    If Not found Is Nothing Then
        MsgBox ProductID & " was Found"
    Else
        MsgBox ProductID & " was NOT Found"
    End If

End Sub

【讨论】:

  • 这将我带到“运行时错误 9,下标超出范围”并突出显示:Set ProductID = Worksheets(1).Cells.Find("ProductID", LookIn:=xlWhole)跨度>
  • 刷新页面。该行应为:Set found = Worksheets(1).Cells.Find(What:=ProductID, LookIn:=xlValues, LookAt:=xlWhole).
猜你喜欢
  • 2021-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多