‘批量遍歷文件夾下某類文件,並統計編號
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