打开一个循环的文件path中的所有excel文件后,有没有办法通过vba创build工作簿variables引用这些文件?

Dim MyFolder As String Dim MyFile As String MyFolder = "C:--" (leaving out the file path) MyFile = Dir(MyFolder & "\*.xlsx") Do While MyFile <> "" Workbooks.Open fileName:=MyFolder & "\" & MyFile MyFile = Dir Loop (see paragraph below) Workbook.Open Dim wbk1 as workbook Set wbk1 = ActiveWorkbook (can reference workbook like this) wbk1.Activate 

我查了几个其他的论坛,发现你可以通过首先打开它们来引用其他工作簿,然后创build一个variables并将其设置为上面第二个代码段中列出的打开的工作簿。

当我试图想办法为这个特定文件path中的所有文件创build引用variables时,我意识到我无法在运行时dynamic地命名不同的variables,以将每个工作簿设置为不同的工作簿variables。

那么,是否有任何替代scheme来完成我想要完成的任务,或者是否有办法dynamic创buildvariables?

下面是你如何做到这一点:(这将它作为一个新的名称模板打开)

 Dim wb1 as Workbook Set wb1 = Workbooks.Add(MyFile) 

或者:(如果工作簿已经打开,这将失败)(如果以后需要保存,则使用此项)

 Dim wb1 as Workbook Set wb1 = Workbooks.Open(MyFile) 

然后你可以像这样创build一个工作表对象:

 Dim ws1 as Worksheet Set ws1 = wb1.Worksheets(1) 

然后,任何时候你想要引用该表上的东西,比如Range或者Cell确保使用Worksheet引用来限定它:

 Dim rng as Range Set rng = ws1.Range("A1:B1") 

您可以使用数组,集合或字典来保存对多个工作簿的引用。
最好打开一个工作簿,做你所需要的,closures它,然后使用相同的variables来打开下一个工作簿。

注:要正确地将工作簿存储在variables中,请使用@brax提供的代码。

但是…这是你要求的:

此代码将打开文件夹中的每个工作簿,然后返回有关每个工作簿的信息。

 Option Explicit 'You wouldn't believe how important this is at the top of your module! Public Sub Test() Dim MyFolder As String Dim MyFiles As Collection Dim wrkBk As Workbook Dim sFile As String Dim secAutomation As MsoAutomationSecurity MyFolder = "C:\" Set MyFiles = New Collection 'We don't want any WorkBook_Open macros to fire when we open the file, 'so remember the current setting and then disable it. secAutomation = Application.AutomationSecurity Application.AutomationSecurity = msoAutomationSecurityForceDisable sFile = Dir$(MyFolder & "*.xls*") Do While Len(sFile) > 0 'We don't want to open the file if it's got the same name as this one. If sFile <> ThisWorkbook.Name Then 'Open the workbook and add it to the collection, give it a key of the file name. Set wrkBk = Workbooks.Open(MyFolder & sFile) MyFiles.Add wrkBk, wrkBk.Name Set wrkBk = Nothing End If sFile = Dir$ Loop 'Reset macro security settings. Application.AutomationSecurity = secAutomation '---------------- 'All files are open and ready to be referenced. '---------------- Dim SingleFile As Variant 'List all details from each file in the immediate Window. For Each SingleFile In MyFiles With SingleFile Debug.Print "Name: " & .Name & " | Sheet Count: " & .Sheets.Count & _ " | Last Row on '" & .Worksheets(1).Name & "' Column A: " & .Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Row End With Next SingleFile 'Get the value from a specific file using the key value (Book7.xlsm) Debug.Print MyFiles("Book7.xlsm").Worksheets("Form").Range("A6") 'Now close all the files. For Each SingleFile In MyFiles Debug.Print "Closing " & SingleFile.Name SingleFile.Close SaveChanges:=False Next SingleFile End Sub