繁体   English   中英

如何打开文件夹中的所有文件(xls和csv格式文件) - VBA

[英]How to open all files in the folder (xls and csv format files) - VBA

我编写了用于将来自多个工作簿的数据合并到一个工作簿的代码,并且代码仅打开xls格式文件,但是一些文件在文件夹中具有csv格式。 如何在文件夹中打开csv和xls文件? 任何建议,它会赞赏

Option Explicit

Sub ImportGroups()
Dim fPATH As String, fNAME As String
Dim LR As Long, LastRow As Long
Dim wb2, wb1 As Workbook, ofs As Worksheet

Set ofs = ThisWorkbook.Sheets("Sheet3")


fPATH = "C:\Users\ashokkumar.d\Desktop\MFI\"       

fNAME = Dir(fPATH & "*.xls")        'get the first filename in fpath

Do While Len(fNAME) > 0
    Set wb1 = Workbooks.Open(fPATH & fNAME)   'open the file

    LastRow = ofs.Range("B" & Rows.Count).End(xlUp).Row
    ofs.Range("B" & LastRow).Offset(1, -1).Value = fNAME

    Sheets("Input").Range("C8:J12").Copy
    ofs.Range("B" & LastRow).Offset(1, 0).PasteSpecial xlPasteValues



    wb1.Close False   'close data workbook
        fNAME = Dir         'get the next filename
Loop


 LR = ofs.Range("C" & Rows.Count).End(xlUp).Row
 ofs.Range("E2:I" & LR).Select
 Selection.NumberFormat = "0.00%"
 Application.ScreenUpdating = True
 ofs.Range("A1:Z" & LR).Select
 With Selection
    WrapText = True
    End With

End Sub

像这样:

fNAME = Dir(fPATH & "*")        'get the first filename in fpath
Do While Len(fNAME) > 0
    dim ext as string, p as integer
    p = inStrRev(fName, ".")
    ext = ucase(mid(fName, p+1))
    if ext = "CSV" or ext = "XLS" or ext = "XLSX" or ext = "XLST" then
        Set wb1 = Workbooks.Open(fPATH & fNAME)   'open the file
        ...
    end if

您可以获取文件夹中的所有文件,然后检查文件是CSV还是xlsx文件。 然后像你一样打开它。

    Option Explicit

    Sub ImportGroups()
    Dim fPATH As String, fNAME As String
    Dim LR As Long, LastRow As Long
    Dim wb2, wb1 As Workbook, ofs As Worksheet

    Set ofs = ThisWorkbook.Sheets("Sheet3")


    fPATH = "C:\Users\ashokkumar.d\Desktop\MFI\"       

    fNAME = Dir(fPATH & "*.*")        'get the first filename in fpath

    Do While Len(fNAME) > 0
If Right(fNAME, 4) = "xlsx" Or Right(fNAME, 4) = ".csv" Then
        Set wb1 = Workbooks.Open(fPATH & fNAME)   'open the file

        LastRow = ofs.Range("B" & Rows.Count).End(xlUp).Row
        ofs.Range("B" & LastRow).Offset(1, -1).Value = fNAME

        Sheets("Input").Range("C8:J12").Copy
        ofs.Range("B" & LastRow).Offset(1, 0).PasteSpecial xlPasteValues



        wb1.Close False   'close data workbook
            fNAME = Dir         'get the next filename
end if
    Loop


     LR = ofs.Range("C" & Rows.Count).End(xlUp).Row
     ofs.Range("E2:I" & LR).Select
     Selection.NumberFormat = "0.00%"
     Application.ScreenUpdating = True
     ofs.Range("A1:Z" & LR).Select
     With Selection
        WrapText = True
        End With

    End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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