VBA遍歷資料夾下檔案檔案實用原始碼
阿新 • • 發佈:2018-12-23
‘批量遍歷資料夾下某類檔案,並統計編號 Sub OpenAndClose() Dim MyFile As String Dim s As String Dim count As Integer MyFile = Dir("d:\data\" & "*.csv") '讀入資料夾中第一個.xlsx檔案 count = count + 1 '記錄檔案的個數 s = s & count & "、" & MyFile Do While MyFile <> " " MyFile = Dir '第二次讀入的時候不用寫引數 If MyFile = "" Then Exit Do '當myfile為空時候說明已經遍歷完了,推出do,否則要重新執行一遍 End If count = count + 1 If count Mod 2 <> 1 Then s = s & vbTab & count & "、" & MyFile Else s = s & vbCrLf & count & "、" & MyFile End If Loop Debug.Print s End Sub ‘遍歷每個檔案,並且修改檔案,先將檔案的名字存在陣列中,然後通過陣列遍歷開啟每個檔案,修改,再關閉檔案~ Sub OpenCloseArray() Dim MyFile As String Dim Arr(100) As String Dim count As Integer MyFile = Dir("D:\data\data2\" & "*.xlsx") count = count + 1 Arr(count) = MyFile Do While MyFile <> "" MyFile = Dir If MyFile = "" Then Exit Do End If count = count + 1 Arr(count) = MyFile '將檔案的名字存在陣列中 Loop For i = 1 To count Workbooks.Open Filename:="d:\data\data2\" & Arr(i) '迴圈開啟Excel檔案 Sheet1.Cells(2, 2) = "alex_bn_lee" '修改開啟檔案的內容 ActiveWorkbook.Close savechanges = True '關閉開啟的檔案 Next ‘要是想要修改每個工作簿的內容可以這樣遍歷一下,顯示將資料夾中的工作簿的名字存到’一個字串陣列中,然後在用For...Next語句遍歷 ‘遍歷某個資料夾中的所有檔案(*.*) ’注意:遍歷的時候,順序完全是按照檔名的順序排的,而不是按照資料夾中檔案的順序~ Sub dlkfjdl() Dim MyFile As String Dim count As Integer count = 1 MyFile = Dir("d:\data\*.*") Debug.Print "1、" & MyFile Do While MyFile <> "" count = count + 1 MyFile = Dir If MyFile = "" Then Exit Do Debug.Print count & "、" & MyFile Loop End Sub