VBA执行代码行,然后抱怨该行超出范围

当我尝试运行此代码时,我明确地得到下标超出范围错误:

Sub CopyData() 'Setup Dim Filename, Pathname As String Dim source As Workbook Dim destination As Workbook Dim nextName As String Pathname = ActiveWorkbook.Path & "\Q1 grades fall 2015-2016-1" Filename = Dir(Pathname & "*.xls") Set source = Workbooks("<name of my file>") Set destination = Workbooks.Open(Pathname & Filename) 'Done with Setup lastPlace = 2 'Iterate through Source rows For sourceRow = 5 To 28 With source.Worksheets("<name of my worksheet>") currName = Cells(sourceRow, 1) 'Iterate through Source columns to collect info 'Columns: ENG = 4; MAT = 7; SCI = 10; SOC = 13; WOR = 16 ENG = Cells(sourceRow, 4).Value MAT = Cells(sourceRow, 7).Value SCI = Cells(sourceRow, 10).Value SOC = Cells(sourceRow, 13).Value WOR = Cells(sourceRow, 16).Value End With With destination.Worksheets("Sheet1") nextName = Split(Cells(lastPlace + 1, 1).Value, ",")(0) MsgBox nextName End With 'If currName = destination's name at lastPlace + 1 Then 'Iterate through Destination to match currName and fill info For destRow = 76 To 99 destination.Worksheets("Sheet1").Activate lastPlace = destRow Next destRow Next sourceRow End Sub 

我的问题在这里发生:

 nextName = Split(Cells(lastPlace + 1, 1).Value, ",")(0) MsgBox nextName 

或者至less,这是VBA SAYS发生的地方。

黄色光标指向第一行。 但这里是我没有得到(除了我的数组中的第一个元素可能超出范围):我得到一个消息框打印出应该是什么值(学生的姓氏)。 我改变它看第二个元素,并再次打印出正确的值(同名学生的名字)。 这与我的excel的格式是一致的。

所以这是我的主要问题:这个错误在哪里,我该如何解决?

但是因为我从昨天下午就开始学习VBA,所以我不会介意从代码中看到任何额外的提示。

先谢谢你!

编辑:

我应该提到,我试图把VBA.Split,而不是。 没有骰子。

您正在使用With … End With语句,但忽略它作为对父工作表的引用的目的。 一个句点(aka .或者句号 )就是把这个父引用传递给With … End With中的成员。

 With destination.Worksheets("Sheet1") nextName = Split(.Cells(lastPlace + 1, 1).Value, ",")(0) MsgBox nextName End With 

注意.Cells而不是Cells

好的,在制作示例文件时,我发现了这个问题。

当我testing我的代码时,我完全忘记了底部的不完整段(你需要向下滚动才能看到,大声笑)。 该段恰好是一个循环,增加索引“lastPlace”,并设置另一个工作表激活(虽然第二部分不应该有所作为我不认为)。

这个循环也嵌套在我的原始循环中,所以我无意中将索引跳到了99。

当然,这就解释了a)为什么我看到一个正确的MsgBox,然后是同一行上的错误(我觉得没有注意到一个循环会导致这样的事情发生,我感到很傻),b)为什么我得到了范围错误(下一行是空白的)。

如果有人想知道为什么我把它放在那里开始,那应该是在当时声明的一端。 但是我很傻,忘了它在那里,仍然影响我的代码。