简体   繁体   中英

After opening all excel files in a file path with a loop, is there any way to reference these files by creating workbook variables through vba?

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

I've checked a couple other forums and found out that you can reference other workbooks by first opening them and then create a variable and set it to the open workbook as listed above in the second code paragraph.

When I tried to think of a way to make reference variables for all files in this specific file path, I realized that I couldn't dynamically name different variables during runtime to set each workbook to a different workbook variable.

So, is there any alternative to accomplishing the task I am trying to complete or is there a way to dynamically create variables?

Here is how you do it: (this opens it as a template with a new name)

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

Alternatively: (this will fail if the workbook is already open) (use this one if you need to be able to save it afterwards)

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

Then you can create a worksheet object like this:

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

Then anytime you want to refer to something on that sheet, like a Range or a Cell make sure to qualify that with the Worksheet reference like this:

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

You could use an array, a collection or a dictionary to hold references to multiple workbooks.
It may be preferable to open a single workbook, do what you need, close it and then use the same variable to open the next workbook.

Note: To correctly store a workbook within a variable use the code supplied by @brax.

But... this is what you asked for:

This code will open each workbook within a folder and then return information about each one.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM