【问题标题】:Loop through folder, and for each workbook copy paste a range to a static workbook遍历文件夹,并为每个工作簿副本粘贴一个范围到静态工作簿
【发布时间】:2014-11-05 17:19:39
【问题描述】:

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

我在选择工作簿时遇到了问题,因此我可以使用它 - 我不断收到超出范围的下标,而且我认为我的文件路径是正确的。我尝试过使用扩展名和不使用扩展名,当我在我的计算机中搜索该扩展名时,它工作正常。有什么想法吗?

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

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

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

【问题讨论】:

    标签: vba loops excel foreach


    【解决方案1】:

    这里的file 是一个Scripting.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
    

    【讨论】:

    • 完美!像魅力一样工作。
    • 不客气。您还应该查看从用户那里获取文件路径(输入)的其他方法。 InputBox 没问题,但如果用户输入错误的路径等,很容易出错。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多