VBA code to open all excel files in a folder

三世轮回 提交于 2021-02-08 08:44:20

问题


I was working with a vba and I'm trying to open all excel files in a folder (about 8-10) based on cell values. I was wondering if this is the right approach to opening it, it keeps giving me syntax error where I wrote the directory. and when I rewrote that section, the vba only shot out the msgbox which meant it had to have looped and did something right? but didn't open any files. Any information will help. Thank you guys so much for taking the time to help me in any way.

Sub OpenFiles()

Dim search As Worksheet
Dim customer As Range
Dim customerfolder As Range

Dim QualityHUB As Workbook

'setting variable references
Set QualityHUB = ThisWorkbook
Set search = Worksheets("Search")
Set customer = Worksheets("Search").Range("$D$1")
Set customerfolder = Worksheets("Search").Range("$D$3")


With QualityHUB

If IsEmpty((customer)) And IsEmpty((customerfolder)) Then

MsgBox "Please Fill out Customer Information and search again"

Exit Sub

End If

End With

With QualityHUB


Dim MyFolder As String
Dim MyFile As String
Dim Directory As String

Directory = "O:\LAYOUT DATA\" & customer & "\" & customerfolder"


MyFile = Dir(Directory & "*.xlsx")


Do While MyFile <> ""

Workbooks.Open Filename:=MyFile

MyFile = Dir()


Loop


MsgBox "Files Open for " + customerfolder + " complete"


End With


End Sub

回答1:


This worked for me perfectly

Sub OpenFiles()

Dim search As Worksheet
Dim customer As Range
Dim customerfolder As Range

Dim QualityHUB As Workbook

'setting variable references
Set QualityHUB = ThisWorkbook
Set search = Worksheets("Search")
Set customer = Worksheets("Search").Range("$D$1")
Set customerfolder = Worksheets("Search").Range("$D$3")


With QualityHUB

If IsEmpty((customer)) And IsEmpty((customerfolder)) Then

    MsgBox "Please Fill out Customer Information and search again"

Exit Sub

End If

End With

With QualityHUB


Dim MyFolder As String
Dim MyFile As String
Dim Directory As String

Directory = "O:\LAYOUT DATA\" & customer & "\" & customerfolder & "\"


MyFile = Dir(Directory & "*.xlsx")

Do While MyFile <> ""

Workbooks.Open Filename:=Directory & MyFile

MyFile = Dir()


Loop


MsgBox "Files Open for " + customerfolder + " complete"


End With


End Sub



one of the issue was, you had to write

Workbooks.Open Filename:=Directory & MyFile

instead of

Workbooks.Open Filename:=MyFile



回答2:


Corrected some issues with your code and cleaned it up, give this a try. I think the big issue was you had an extra double-quote, and you missing the ending \ in the Directory line:

Sub OpenFiles()

    Dim QualityHUB As Workbook
    Dim search As Worksheet
    Dim customer As String
    Dim customerfolder As String
    Dim Directory As String
    Dim MyFile As String

    'setting variable references
    Set QualityHUB = ThisWorkbook
    Set search = QualityHUB.Worksheets("Search")
    customer = search.Range("$D$1").Value
    customerfolder = search.Range("$D$3").Value

    If Len(Trim(customer)) = 0 Or Len(Trim(customerfolder)) = 0 Then
        MsgBox "Please Fill out Customer Information and search again"
        Exit Sub
    End If


    Directory = "O:\LAYOUT DATA\" & customer & "\" & customerfolder & "\"   '<--- This requires the ending \
    MyFile = Dir(Directory & "*.xlsx")

    Do While Len(MyFile) > 0
        Workbooks.Open Filename:=Directory & MyFile
        MyFile = Dir()
    Loop

    MsgBox "Files Open for " + customerfolder + " complete"

End Sub



回答3:


I found this code online and it will open all the excel files in a folder, you can adapt the code to apply a function to the workbook, once it is open.

Option Explicit

Type FoundFileInfo
    sPath As String
    sName As String
End Type

Sub find()
Dim iFilesNum As Integer
Dim iCount As Integer
Dim recMyFiles() As FoundFileInfo
Dim blFilesFound As Boolean

blFilesFound = FindFiles("G:\LOCATION OF FOLDER HERE\", _
       recMyFiles, iFilesNum, "*.xlsx", True)
End Sub

Function FindFiles(ByVal sPath As String, _
    ByRef recFoundFiles() As FoundFileInfo, _
    ByRef iFilesFound As Integer, _
    Optional ByVal sFileSpec As String = "*.*", _
    Optional ByVal blIncludeSubFolders As Boolean = False) As Boolean
    Dim iCount As Integer           '* Multipurpose counter
    Dim sFileName As String         '* Found file name
    Dim wbResults, file, WS_Count, i, gcell, col, finRow, wbCodeBook As Workbook, lCount, name, looper
    Dim WorksheetExists
    Set wbCodeBook = ThisWorkbook

    '*
    '* FileSystem objects
    Dim oFileSystem As Object, _
        oParentFolder As Object, _
        oFolder As Object, _
        oFile As Object

    Set oFileSystem = CreateObject("Scripting.FileSystemObject")
    On Error Resume Next
    Set oParentFolder = oFileSystem.GetFolder(sPath)
    If oParentFolder Is Nothing Then
        FindFiles = False
        On Error GoTo 0
        Set oParentFolder = Nothing
        Set oFileSystem = Nothing
        Exit Function
    End If
    sPath = IIf(Right(sPath, 1) = "\", sPath, sPath & "\")
    '*
    '* Find files
    sFileName = Dir(sPath & sFileSpec, vbNormal)
    If sFileName <> "" Then
        For Each oFile In oParentFolder.Files
            If LCase(oFile.name) Like LCase(sFileSpec) Then
                iCount = UBound(recFoundFiles)
                iCount = iCount + 1
                ReDim Preserve recFoundFiles(1 To iCount)
                file = sPath & oFile.name
                name = oFile.name
            End If
                On Error GoTo nextfile:
                Set wbResults = Workbooks.Open(Filename:=file, UpdateLinks:=0)


''insert your code here


               wbResults.Close SaveChanges:=False
nextfile:
        Next oFile
        Set oFile = Nothing         '* Although it is nothing
    End If
    If blIncludeSubFolders Then
        '*
        '* Select next sub-forbers
        For Each oFolder In oParentFolder.SubFolders
            FindFiles oFolder.path, recFoundFiles, iFilesFound, sFileSpec, blIncludeSubFolders
        Next
    End If
    FindFiles = UBound(recFoundFiles) > 0
    iFilesFound = UBound(recFoundFiles)
    On Error GoTo 0
    '*
    '* Clean-up
    Set oFolder = Nothing           '* Although it is nothing
    Set oParentFolder = Nothing
    Set oFileSystem = Nothing

End Function
Function SSCGetColumnCodeFromIndex(colIndex As Variant) As String
    Dim tstr As String
    Dim prefixInt As Integer
    Dim suffixInt As Integer
    prefixInt = Int(colIndex / 26)
    suffixInt = colIndex Mod 26
    If prefixInt = 0 Then
        tstr = ""
    Else
        prefixInt = prefixInt - 1
        tstr = Chr(65 + prefixInt)
    End If
    tstr = tstr + Chr(65 + suffixInt)
    SSCGetColumnCodeFromIndex = tstr
End Function
Function GetColNum(oSheet As Worksheet, name As String)
Dim Endrow_Col, i
'For loop to get the column number of name
Endrow_Col = oSheet.Range("A1").End(xlToRight).Column
oSheet.Select
oSheet.Range("A1").Select
For i = 0 To Endrow_Col - 1 Step 1
If ActiveCell.Value <> name Then
    ActiveCell.Offset(0, 1).Select
ElseIf ActiveCell.Value = name Then
    GetColNum = ActiveCell.Column
    Exit For
    End If
Next i
End Function
Function ShDel(name As String)

End If
End Function


来源:https://stackoverflow.com/questions/39208708/vba-code-to-open-all-excel-files-in-a-folder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!