VBA运行时错误9使用Sheet

时间:2015-05-20 18:16:33

标签: excel vba excel-vba excel-2010

所以这里我的VBA代码是我的函数的一部分,但每当我运行它时,我都会收到以下错误:

Run-Time error '9': Subscript out of range

实际工作表存在。在侧面板上的vba编辑器中,它显示为Sheet2(Data_Sheet)。在该面板的详细信息中,它将(Name)显示为 Sheet 11 ,将 Name 显示为 Data_Sheet 。有没有人知道这个错误的可能来源?我的代码如下:

With Sheets("Data_Sheet")

        'this searches just row 1
        Set header_cell_1 = .Rows(1).Find(What:="One", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
        Set header_cell_2 = .Rows(1).Find(What:="Two", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
        Set header_cell_3 = .Rows(1).Find(What:="Three", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
        Set header_cell_4 = .Rows(1).Find(What:="Four", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
        Set header_cell_5 = .Rows(1).Find(What:="Five", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
        Set header_cell_6 = .Rows(1).Find(What:="Six", lookat:=xlWhole, MatchCase:=False, searchformat:=False)
        Set header_cell_7 = .Rows(1).Find(What:="Seven", lookat:=xlWhole, MatchCase:=False, searchformat:=False)

        col_1 = header_cell_1.Column
        col_2 = header_cell_2.Column
        col_3 = header_cell_3.Column
        col_4 = header_cell_4.Column
        col_5 = header_cell_5.Column
        col_6 = header_cell_6.Column
        col_7 = header_cell_7.Column

    End With

1 个答案:

答案 0 :(得分:4)

从评论开始,宏正在从PERSONAL.XSLB工作簿运行,因此它正在尝试在其中找到Sheets("Data_sheet"),并且显然没有找到,因为它是在另一个工作簿中 - > Subscript out of range

要修复,始终使用您使用的Object的完整参考:

With Workbooks("myWorkbook.xlsm").Sheets("Data_sheet") '<-- explicitly saying in which workbook it must look for the sheet

End With

或者,请记住:

  • ThisWorkbook引用代码运行的工作簿。在您的情况下,它将引用PERSONAL.XLSB;
  • ActiveWorkbook引用当前活动的工作簿。使用风险很大(通常,您应该知道要定位的工作簿)。但是在某些情况下,您希望代码有意在活动工作簿上运行(请参阅加载项示例:代码从加载项运行,但您希望加载项在工作簿上运行从中使用)。

警告:

常见错误使用任何引用,例如:

With Sheets("Data_Sheet") '<-- of which workbook? 

在这种情况下,VBA使用ActiveWorkbook回答问题本身,ActiveWorkbook是默认对象。只有当明确地想要从"2d641b7c-3d74-4cfa-8267-d5a01ed2614b"运行时,你才应该这样做;否则,始终引用该对象以避免与此相关的任何错误。