VBA运行时错误9与工作表

所以在这里我有VBA代码是我的函数的一部分,但是每当我运行它,我得到以下错误:

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

实际的工作表存在。 在侧面板的vba编辑器中,它显示为Sheet2(Data_Sheet)。 在该面板的详细信息中,它显示(名称)为工作表11名称显示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 

从注释来看,这个macros是从PERSONAL.XSLB工作簿运行的,因此它试图在其中findSheets("Data_sheet") ,显然没有find,因为它进入了另一个工作簿 – >下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运行,你应该像这样离开; 否则, 总是引用该对象以避免与此相关的任何错误。