循环文件夹,并为每个工作簿复制将范围粘贴到静态工作簿

时间:2014-09-11 16:43:31

标签: excel vba loops excel-vba foreach

我正在尝试遍历工作簿列表,然后为每个工作簿将当前工作簿中的工作表上的多个范围复制并粘贴到主工作簿。

我在选择工作簿时遇到问题,所以我可以使用它 - 我不断下标范围,我认为我的文件路径是正确的。我尝试使用扩展程序,但没有,当我在计算机中搜索该扩展程序时,它运行正常。有什么想法吗?

我试图打开该文件(这是一个变体)但这不起作用,因为我不认为它被认为是一本工作簿。我试图打开该文件的名称,但这也不起作用。最后,我将一个范围命名为实际名称,并尝试做Workbooks(APath)。打开,但这不起作用。我错过了什么?谢谢!

我将文件路径切换为假文件路径。

Dim fso As FileSystemObject
Dim MyObj As Object, MySource As Object, file As Variant
Set fso = New FileSystemObject

FilePath = InputBox(Prompt:="Type the folder file path: this:C:\Users\A\Desktop \test_folder\", Title:="UPDATE MACRO")

Set MySource = fso.GetFolder(FilePath)
For Each file In MySource.Files

'This does not work...
file.Activiate
file.Open

'So I tried this, and still did not work. Any ideas?
APath = "\\file\A\Template_1.xlsx"

MsgBox FilePath & file.Name
actwb = FilePath & file.Name

Workbooks(APath).Open
Workbooks(APath).Activate
MsgBox ActiveWorkbook

1 个答案:

答案 0 :(得分:1)

此处的fileScripting.File对象,不是 Excel工作簿(尚未)。因此,没有ActivateOpen方法。您必须将其作为工作簿对象打开它才能使用工作簿方法。要在Excel 中打开,请执行以下操作:

Dim wb as Workbook

For Each file In MySource.Files


    Set wb = Workbooks.Open(file.path)

    'now you can do stuff to the wb Workbook
    MsgBox wb.Name 'etc...

    'when you're done with the workbook, save it/close it:
    wb.Save 'or omit this line if you don't want to save it, etc.
    wb.Close 

Next