为什么我提供了一个对象时,我得到了超级VBA的“对象必需”错误?

时间:2012-05-20 22:34:58

标签: vba object excel-vba required excel

我的主宏调用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 个答案:

答案 0 :(得分: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