[英]How to open all files in the folder (xls and csv format files) - VBA
I have written code for consolidate the data from multiple workbook to one workbook and the code only opening the xls format files but some files have csv format in the folder. 我编写了用于将来自多个工作簿的数据合并到一个工作簿的代码,并且代码仅打开xls格式文件,但是一些文件在文件夹中具有csv格式。 how to open csv and xls files in the folder?
如何在文件夹中打开csv和xls文件? Any suggestion it would appreciated
任何建议,它会赞赏
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
Just like this: 像这样:
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
You can get all Files in the Folder and check then if the file is an CSV or xlsx File. 您可以获取文件夹中的所有文件,然后检查文件是CSV还是xlsx文件。 And then Open it like you did.
然后像你一样打开它。
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.