打开时重定名工作簿

时间:2015-06-24 23:45:44

标签: excel vba excel-vba excel-vba-mac

我正在编写一个模块,用于打开文件夹中的每个工作簿并从中复制一些信息。它在文件夹中的大多数文件上运行顺畅,但是当模块打开时,某些工作簿会显示不同的名称。我的代码如下

Sub AutoUpdate()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Sheets(1).Cells(1, 10).Value = Now()
'refreshes timestamp
Dim counter As Integer
Dim form
form = Dir("Macintosh HD:Users:user:Documents:Folder:")
'Finds first form in folder
counter = 1
Do Until form = ""
    Workbooks.Open ("Macintosh HD:Users:user:Documents:Folder:" & form)
    Workbooks("Inventory.xlsm").Sheets(2).Cells(counter, 1).Value = Workbooks(form).Sheets(1).Range("D3").Value
    Workbooks("Inventory.xlsm").Sheets(2).Cells(counter, 2).Value = Workbooks(form).Sheets(1).Range("D5").Value
    Workbooks("Inventory.xlsm").Sheets(2).Cells(counter, 3).Value = Workbooks(form).Sheets(1).Range("D1").Value
    Workbooks("Inventory.xlsm").Sheets(2).Cells(counter, 4).Value = Workbooks(form).Sheets(1).Range("D2").Value
    Workbooks("Inventory.xlsm").Sheets(2).Cells(counter, 5).Value = Workbooks(form).Sheets(1).Range("L69").Value
    Workbooks("Inventory.xlsm").Sheets(2).Cells(counter, 6).Value = Workbooks(form).Sheets(1).Range("K36").Value
    Workbooks("Inventory.xlsm").Sheets(2).Cells(counter, 7).Value = Workbooks(form).Sheets(1).Range("C37").Value
    Workbooks(form).Close
    counter = counter + 1
    form = Dir
    'cycles through all forms
Loop
Workbooks("Inventory.xlsm").Sheets(2).Range("A:G").Sort Key1:=Workbooks("Inventory.xlsm").Sheets(2).Range("A:A"), Order1:=xlAscending, Key2:=Workbooks("Inventory.xlsm").Sheets(1).Range("C:C"), Order2:=xlAscending, Orientation:=xlSortRows
Application.ScreenUpdating = True
Application.DisplayAlerts = False
End Sub

这将从前45个工作簿中提取数据,然后返回“运行时错误9下标超出范围”。打开的工作簿显示为名称read作为文件名,附加两个看似随机的数字。当我手动打开文件时,名称将作为文件名读取。

1 个答案:

答案 0 :(得分:0)

您应该在打开每个文件后使用Workbooks(form),而不是使用ActiveWorkbook来访问数据。您还可以使用ActiveWorkbook.Close

关闭打开的工作簿

您还可以定义如下变量: - Dim wb As Workbook然后使用打开的工作簿分配变量,如下所示: -

set wb = Workbooks.Open ("Macintosh HD:Users:user:Documents:Folder:" & form)

然后,您可以使用wb引用该工作簿。 e.g。

Workbooks("Inventory.xlsm").Sheets(2).Cells(counter, 1).Value = wb.Sheets(1).Range("D3").Value

然后关闭它: -

wb.Close

不要忘记成为一名优秀的资源公民并在最后释放记忆:

set wb = Nothing