对象变量未设置

时间:2015-10-08 00:00:38

标签: excel vba excel-vba

为什么赢得aCell_1设定?

[编辑]

以下是简化代码的两个版本;在第二个好人帮助我找到解决方案。当我将该解决方案应用于我的实际代码时,它没有工作......

上下文:代码搜索以编程方式生成的Excel输出,其中列名始终相似但位置可能会发生变化。最终我想让UserForm按钮显示/隐藏列,无论它们在哪里,但如果我无法获取变量来设置它就不会发生。

之前的简化代码:

Public aCell_1 As Range

Private Sub setvars()

'Specifies the column header to search for
        Dim strSearch_1 As String
        strSearch_1 = "Target ID"

 'Searches row 1 for the chosen string,  and sets var to that range
        Set aCell_1 = Rows(1).Find(What:=strSearch_1, LookIn:=xlFormulas, _
        LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)
        If aCell_1 Is Nothing Then
            MsgBox "I didn't find " & strSearch_1
        End If
End Sub
Private Sub DoStuffWithVars()

        MsgBox aCell_1   'this is where excel reports object variable not set

End Sub

以下简化代码:

 Public aCell_1 As Range

    Private Sub setvars()

    'Specifies the column header to search for
            Dim strSearch_1 As String
            strSearch_1 = "Target ID"

     'Searches row 1 for the chosen string,  and sets var to that range
            Set aCell_1 = Rows(1).Find(What:=strSearch_1, LookIn:=xlFormulas, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)
            If aCell_1 Is Nothing Then
                MsgBox "I didn't find " & strSearch_1
            End If
    End Sub
    Private Sub DoStuffWithVars()
            setvars
            MsgBox aCell_1   'the variable is now successfully set!

    End Sub

实际代码仍然存在:

   Public aCell_1 As Range
Private sub userform_initialize()
  setvars
end sub

Private Sub setvars()
  'aCell_1 = TargetID
    Dim strSearch_1 As String   'Define local Vars
    strSearch_1 = "Target ID"   'Specify Field Name
    Set aCell_1 = Rows(1).Find(What:=strSearch_1, LookIn:=xlFormulas, _
    LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)              'Search row 1 for string,  and set var to that range
                                                        'use < aCell_x.EntireColumn.Hidden = True/False > to set
    If aCell_1 Is Nothing Then
               errorcode = 1
    End If
end sub
Private Sub tglTargetID_Click()
    setvars                                     'same fix applied
    If tglTargetID.Value = True Then
        'This area contains the things you want to happen when the toggle button is depressed
        'The button is blue; depressed = true
        aCell_1.EntireColumn.Hidden = False           'object variable not set HERE
        tglTargetID.BackColor = &H80000002
    Else
         'This area contains the things you want to happen when the toggle button is not depressed
         'The Button is white
        aCell_1.EntireColumn.Hidden = True
        tglTargetID.BackColor = &H80000004

    End If
End Sub

0 个答案:

没有答案