【问题标题】:why Iam I getting excel VBA's "object required" error when I have supplied an object?为什么我在提供对象时收到 excel VBA“需要对象”错误?
【发布时间】:2012-05-20 22:34:57
【问题描述】:

我的主宏调用 4 个子宏,然后执行一行代码,然后生成“需要对象”错误。我不知道为什么,因为我正在提供一个对象(至少我认为我是)。

我的代码如下所示:

Sub main_macro()
    Call Mac1
    Call Mac2
    Call Mac3
    Call Mac4
    Range("B" & input1.Row).Value = Range("C" & scenario1.Row)     <-- this generates the error
End Sub

Sub Mac1()
   Dim input1 As Range
End Sub

Sub Mac2()
   Dim scenario1 As Range
End Sub

Sub Mac3()
   Set input1 = Range("A:A").Find("location1", LookIn:=xlValues, LookAt:=xlWhole)
End Sub

Sub Mac4()
   Set scenario1 = Range("A:A").Find("location2", LookIn:=xlValues, LookAt:=xlWhole)
End Sub

【问题讨论】:

  • 与其将它们全部设为宏并调用它们,不如将每个宏中的代码放入主宏中。变量仅在子范围内,除非您将它们签名为“全局”变量。
  • 是的,我实际上一开始就在 1 个宏中完成了所有操作,但是当我多次这样做时,我得到了“程序太大”的错误,所以我决定将其分解。跨度>
  • 看起来像在模块顶部添加“公共”声明修复了它。谢谢!
  • 这不是我的意思吗? :) 如果您使用.Find,请务必正确处理输出,如下所示。

标签: vba object excel required


【解决方案1】:

这是你正在尝试的吗?

您的变量在过程中声明,其他人无法使用。因此你他们没有初始化。

Option Explicit

Sub main_macro()
    Dim input1 As Range, scenario1 As Range

    With Sheets("Sheet1") '<~~ Change this to the relevant Sheet
        Set input1 = .Range("A:A").Find("location1", LookIn:=xlValues, LookAt:=xlWhole)

        If input1 Is Nothing Then
            MsgBox "location1 not found"
            Exit Sub
        End If

        Set scenario1 = .Range("A:A").Find("location2", LookIn:=xlValues, LookAt:=xlWhole)

        If scenario1 Is Nothing Then
            MsgBox "location2 not found"
            Exit Sub
        End If

        .Range("B" & input1.Row).Value = Range("C" & scenario1.Row).Value
    End With
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-11
    • 2018-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多