‘批量遍历文件夹下某类文件,并统计编号
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