【问题标题】:Searching for a value from a specific cell on another sheet从另一个工作表上的特定单元格中搜索值
【发布时间】:2018-10-06 02:36:01
【问题描述】:

我正在使用用户表单来输入数据,在某一时刻,部分数据被复制到工作簿中的一张工作表中。

然后我的代码需要使用工作表中的一个值来检查该值是否出现在另一张工作表上,如果确实如此,它将链接到该值的值复制到原始工作表,然后填充用户表单,以便进一步的信息可以被俘虏。

如果我激活 on error resume next 一切正常,除了选项卡功能停止在用户窗体上工作,如果我在没有 on error resume next 的情况下运行它,我会收到运行时错误:

'91' 对象变量或未设置块变量。

我该如何解决这个问题?

Sub Find_7_day()

        Dim vfind

        Dim rng As Range

        Sheets("Test Data").Select
        Sheets("Test Data").Range("$E$3").Select
        vfind = ActiveCell

        'On Error Resume Next
        Call Sheet
        Set rng = Cells.Find(What:=vfind, After:=ActiveCell,        LookIn:=xlValues, _
             LookAt:=xlWhole, SearchOrder:=xlByRows,     SearchDirection:=xlNext, _
             MatchCase:=True, SearchFormat:=False).Activate

       If ActiveCell = vfind Then
            Call Old_7_day
            Call Form_7_day_fill
        Else
            Sheets("Test Data").Select
        End If


End Sub

【问题讨论】:

  • 找不到您的值,因此您正在尝试激活一个不存在的范围。 Sheet 是什么?
  • 删除.Activate并测试If Not rng Is Nothing Then
  • 就像@TimWilliams 提到的那样,您不能同时设置范围并激活它。删除.Activate ..如果你想选择单元格,那么下一行可以是rng.select---"Find Data in another sheet
  • @SJR Sheet 是另一段代码,可将您带到要在其中进行搜索的工作表,大约有 15 个工作表需要检查,因此其中一个输入用于定位工作表和这段代码的另一个

标签: vba excel


【解决方案1】:

你不能同时声明和.Activate一个变量range

    Dim rng As Range

    Set rng = Cells.Find(What:=vfind, After:=ActiveCell, LookIn:=xlValues, _
         LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
         MatchCase:=True, SearchFormat:=False).Activate

建议,避免使用.SelectActivate,这里解释How to Avoid the Select Method in VBA & Why

代码:

Sub Find_7_day()

        Dim vfind As String
        Dim rng As Range

        vfind = Sheets("Test Data").Range("$E$3").Value

        Call Sheet

        Set rng = Cells.Find(What:=vfind, LookIn:=xlValues, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, _
        MatchCase:=True, _
        SearchFormat:=False)

        If rng Is Nothing Then
        MsgBox vfind & " " & "dont exist"
        Exit Sub
        End If

       If rng.Value = vfind Then
            Call Old_7_day
            Call Form_7_day_fill
        Else
            Sheets("Test Data").Select
        End If

        Exit Sub

End Sub

【讨论】:

  • @SJR 谢谢,更新了我的答案以检查 rng 是否为空
  • 抱歉,是我不小心。我现在已经扭转了它。似乎如果你先投反对票,然后再投赞成票,它会从 -1 变为 +1!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-13
  • 1970-01-01
  • 2019-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多