【发布时间】:2014-09-11 15:48:10
【问题描述】:
好的,抱歉,如果代码标签不起作用,我已经有一段时间没有上 Stack Overflow 了。无论如何,这是我遇到的问题,我很确定我知道发生了什么,但我可以使用一些帮助。下面的代码我基本上是在打开一个 excel 工作簿,它将文件路径存储到我的计算机上的不同工作簿,我将它们放入一个数组中。该数组通过我正在使用的调试消息框正确存储数据,但是当它到达“Set tempBook = filePathArray(i, 1)”行时,我得到错误“424 Object Required”。现在我知道了一个事实,即我在 Set tempBook 行中查看的数组中的项目正在查看文件路径。我的理论是存储在数组中的信息可能具有特殊格式,不允许 Set tempBook 将字符串识别为文件路径。抱歉,如果这真的很简单,这是我第一次使用 VBA 和宏,我更喜欢 Java 和 C#。无论如何,男孩和女孩的任何帮助将不胜感激。另外为了安全起见,我在发布之前更改了 filePathBook 的文件路径信息。
回顾一下:
我正在从我桌面上的工作簿中检索文件路径信息并将其存储到一个数组中,该工作簿中的每个单元格都保存着该工作簿的完整文件路径
然后我正在运行一个循环,该循环将遍历数组,在循环期间一次 1 个项目,并尝试单独拉出每个文件路径,获取一些数据,然后使用下一个文件路径再次执行在数组中。
我得到的错误是当它试图从数组中拉出第一个文件路径并将其放入设置为工作簿的变量中时,我收到错误“424 Object Required”。
我有一个调试消息框,所以我知道正在查看的位置包含正确的文件路径信息,但我相信数组格式可能会导致问题。
任何有助于缓解此问题的帮助将不胜感激。
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
【问题讨论】: