這段代碼是讀取一個檔案夾下的所有檔案,也可以根據副檔名篩選其它格式的.
‘有了檔案名稱,就是開啟檔案,獲得每個檔案的SHEET名字.然後寫到你想要的地方
Sub Macro1()
Dim myDialog As FileDialog, oFile As Object, strName As String, n As Integer
Dim FSO As Object, myFolder As Object, myFiles As Object ,Dim fn$
Set myDialog = Application.FileDialog(msoFileDialogFolderPicker)
n = 1
With myDialog
If .Show <> -1 Then Exit Sub
Set FSO = CreateObject(“Scripting.FileSystemObject“) ‘這是檔案夾選擇,點選到你存放檔案的那個
Set myFolder = FSO.GetFolder(.InitialFileName)
Set myFiles = myFolder.Files
For Each oFile In myFiles
strName = UCase(oFile.Name)
strName = VBA.Right(strName, 3)
If strName = “xls“ Or strName = “XLS“ Then ‘這是副檔名選擇
‘下面就可接著寫開啟檔案讀取資料再寫入的語句了,如下:
fn = myFolder & “/“ & oFile.Name
Workbooks.Open Filename:=fn
Worksheets(1).Select ‘假設你讀取SHEET1的資料
RANGE_ = Range(“A2:F50“) ‘需要資料的地區,自己修改
Windows(“外部表格資料自動匯入.xls“).Activate ‘這個是新表的檔案名稱,自己修改下
Worksheets(n).Select ‘開啟第幾個檔案就選擇SHEET幾,如果沒有可用ADD代碼添加
Range(“a2:f5“) = RANGE_ ‘寫入資料
Workbooks(2).Close
n = n + 1
End If
Next
End With
End Sub