VBA-Excel从数组结构中获取文件path

好吧,大家抱歉,如果代码标记不起作用我有没有在堆栈溢出有时。 无论如何,这是我遇到的问题,我很确定我知道发生了什么,但我可以使用一些帮助。 下面的代码我基本上是打开一个Excel工作簿,将存储到我的电脑上的不同工作簿的文件path,我把它们放入一个数组。 该数组通过我正在使用的debugging消息框正确地存储数据,但是当它到达“Set tempBook = filePathArray(i,1)”行时,我得到错误“424 Object Required”。 现在我知道一个事实,我在Set tempBook行看到的数组中的项正在查看一个文件path。 我的理论是存储在数组中的信息可能具有特殊的格式,不允许Set tempBook将string识别为文件path。 对不起,如果这真的很简单,这是我第一次使用VBA和macros的我更喜欢Java和C#。 无论如何,男孩和女孩的任何帮助将不胜感激。 同样为了安全性,我在发布之前更改filePathBook的文件path信息。

回顾一下:

我从桌面上的工作簿中检索文件path信息并将其存储到数组中,该工作簿中的每个单元都保存着一个到工作簿的完整文件path

然后我运行一个循环,循环遍历数组,在循环中一次一个项目,并试图单独拉出每个文件path,获取一些数据,然后再次使用数组中的下一个文件path。

我得到的错误是当它试图将第一个文件path拉出数组,并将其放置到一个variables被设置为一个工作簿,我得到错误“424对象要求”。

我有一个debugging消息框,所以我知道正在查看的位置是住房正确的文件path信息,但我相信数组格式可能会导致一个问题。

任何帮助缓解这个问题将不胜感激。

Sub get_data_from_file() Dim actBook As Workbook 'active workbook Dim filePathBook As Workbook 'filepath workbook Dim pasteCounter As Integer 'paste counting variable in loop Dim counter As Integer 'loop counter 'This sets the workbook the macro is in to be the active workbook to paste too Set actBook = ActiveWorkbook 'Turn off screen update to speed up macro and make it not seem like the screen flashes Application.ScreenUpdating = False 'set the filePathBook to point to the workbook storing the file paths for other books Set filePathBook = Workbooks.Open("C:directory info\filePathBook") Dim filePathArray As Variant 'declare array 'retrieve data from range cells and store in array, these are the file paths for other books filePathArray = filePathBook.Sheets("Sheet1").Range("a1:a2").Value 'Save and close filePathBook filePathBook.Save filePathBook.Close pasteCounter = 1 'initialize paste counter variable, it's used to move cell paste locations 'declare another workbook to use as the temporary variable in the loop to open and retrieve info from each workbook in the array Dim tempBook As Workbook 'Looping structure to look at array and perform functions. For i = 1 To UBound(filePathArray) MsgBox filePathArray(i, 1) 'Debugging purposes: files are being stored properly Set tempBook = filePathArray(i, 1) 'get first workbook filepath and store in tempBook tempBook.Sheets("Sheet1").Range("a1:a4").Copy 'Copy cells a1:a4 from workbook actBook.Sheets("Sheet1").Activate 'Activate current book, this ensures it is always active in each run of the loop ActiveSheet.Cell(a, pasteCounter).Select 'Select proper cell to paste values down from Selection.PasteSpecial Paste:=xlPasteValues 'Paste Values pasteCounter = pasteCounter + 4 'increment paste counter to select cells below pasted cells each iteration 'save and close tempBook tempBook.Save tempBook.Close Next i 'Turn screen updating back on Application.ScreenUpdating = True End Sub 

 Set tempBook = filePathArray(i, 1) 

在这里你试图把一个Variant / String赋给一个Workbook对象

 Set tempBook = Workbooks.Open( filePathArray(i, 1) ) 

可能是你需要的