为什么我在提供对象时会收到 excel VBA 的“需要对象”错误?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10677791/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 16:12:44  来源:igfitidea点击:

why Iam I getting excel VBA's "object required" error when I have supplied an object?

vbaobjectexcel-vbarequiredexcel

提问by GideonShalev

My main macro calls 4 sub macros and then executes a single line of code that then generates the "object required" error. I can't figure out why, as I am supplying an object (at least I think I am).

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

My code looks like this:

我的代码如下所示:

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

回答by Siddharth Rout

Is this what you are trying?

这是你正在尝试的吗?

Your variables are declared inside procedures and are not available to others. And hence you they don't get to initialize.

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

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