尝试从工作簿列表中迭代一些工作簿,超出范围错误

我有个问题。 我猜先编写代码比较容易,然后解释它,所以在这里:

Sub Test() Dim myHeadings() As String Dim i As Long Dim path As String Dim pathtwo As String Dim currentWb As Workbook Dim openWb As Workbook Dim openWs As Worksheet Set currentWb = ActiveWorkbook path = "C:\pathto\" pfile = Split("File1,File2,File3", ",") myHeadings = Split("Januari,Februari,Mars,April,Maj,Juni,Juli,Augusti,September,Oktober,November,December", ",") For j = 0 To UBound(pfile) pathtwo = path & pfile(j) & ".xlsx" i = 0 If IsFile(pathtwo) = True Then For i = 0 To UBound(myHeadings) Set openWb = Workbooks.Open(pathtwo) Set openWs = openWb.Sheets(myHeadings(i)) If openWs.Range("C34") = 0 Then currentWb.Sheets("Indata").Cells(70, i + 27 + 12*j.Value = "" Else currentWb.Sheets("Indata").Cells(70, i + 27 + 12*j).Value = openWs.Range("C34") End If Next i End if Workbooks(openWb.Name).Close Next j End sub 

我想从pfile列表中select一个文件,迭代myHeadings中定义的所有表格,并在C34中扣除值(实际上,扣除了更多的值,但要保持较短的值)。 在这之后,我想closures文件,转到下一个文件,并做同样的事情,直到所有的三个文件(再次,实际上有更多,其中一些还没有存在)。

函数“IsFile”是

 Function IsFile(fName As String) As Boolean 'Returns TRUE if the provided name points to an existing file. 'Returns FALSE if not existing, or if it's a folder On Error Resume Next IsFile = ((GetAttr(fName) And vbDirectory) <> vbDirectory) End Function 

由iDevlop在stackoverflow,在这个线程: VBA检查文件是否存在

我有这个原因

  currentWb.Sheets("Indata").Cells(70, i + 27 + 12*j).Value = openWs.Range("C34") 

是因为我想开始把我的数据写入到AA70(70行,27列)的currentWb中。 j * 12是因为它是“周期性”,取决于它是哪个文件(文件file1对应于2015,file2到2016等),因此在我的摘要中有月份和年份。

问题出现了,但是当我运行这个macros,在火星表的第一个文件我超出范围,但是在我添加文件的迭代之前,在第一个文件没有任何下标超出范围。 有没有人可以看到这是怎么回事?

请注意,缩进等可能有点closures,因为我从一个更大的文件中复制了这个文件,其中有许多行之间使用不相关的代码。

这不是你的具体问题的正确答案,但这是我做了类似的事情,可能会帮助你看到我是如何做到的。 基本上这是做什么打开CSV并复制整个工作表并粘贴到工作簿。 我正在整合像20个CSV转储到1个工作簿,以便更容易挖掘的东西。

关于Dir()

您可以使用2个参数或不带参数来调用Dir。 你用2个参数初始化path和属性(这是可选的)。 第二次我在这个子目录里叫迪尔,没有任何争论。 这是做什么是获取后续的文件。

 Sub Add_Sheets() Dim ws As Worksheet Dim PasteSheet As Worksheet Dim wb As Workbook Set wb = Application.Workbooks.Open("C:\Users\Desktop\CSV\All.xlsx") 'Location of where you want the workbook to be StrFile = Dir("c:\Users\Desktop\CSV\*.csv") 'Dir of where all the CSVs were. Do While Len(StrFile) > 0 Debug.Print StrFile Application.Workbooks.Open ("c:\Users\Desktop\CSV\" & StrFile) Set ws = ActiveSheet ws.Range("A1:C" & rows.Count).Select 'Selecting Specific content on the worksheet Selection.Copy wb.Activate wb.Worksheets.add(After:=Worksheets(Worksheets.Count)).name = StrFile 'Setting the sheet name to the name of the CSV file Range("A1").PasteSpecial Paste:=xlPasteValues StrFile = Dir Loop End Sub