用dir函数加上循环即可。比如将D:\ABC文件夹内的所有文件显示到A列,代码如下:
Sub 遍历所有文件()Dim Fn$, N%
Fn = Dir("D:\ABC\*.*")
While Fn <> ""
N = N + 1
Range("A" & N) = Fn
Fn = Dir
Wend
End Sub
Sub Test()Dim MyName, Dic, Did, I, T, F, TT, MyFileName
T = Time
Set Dic = CreateObject("Scripting.Dictionary") '创建一个字典对象
Set Did = CreateObject("Scripting.Dictionary")
Dic.Add ("D:\My Documents\"), ""
I = 0
Do While I < Dic.Count
Ke = Dic.keys '开始遍历字典
MyName = Dir(Ke(I), vbDirectory) '查找目录
Do While MyName <> ""
If MyName <> "." And MyName <> ".." Then
If (GetAttr(Ke(I) & MyName) And vbDirectory) = vbDirectory Then '如果是次级目录
Dic.Add (Ke(I) & MyName & "\"), "" '就往字典中添加这个次级目录名作为一个条目
End If
End If
MyName = Dir '继续遍历寻找
Loop
I = I + 1
Loop
Did.Add ("文件清单"), "" '以查找D盘My Documents下所有EXCEL文件为例
For Each Ke In Dic.keys
MyFileName = Dir(Ke & "*.xls")
Do While MyFileName <> ""
Did.Add (Ke & MyFileName), ""
MyFileName = Dir
Loop
Next
For Each Sh In ThisWorkbook.Worksheets
If Sh.Name = "XLS文件清单" Then
Sheets("XLS文件清单").Cells.Delete
F = True
Exit For
Else
F = False
End If
Next
If Not F Then
Sheets.Add.Name = "XLS文件清单"
End If
Sheets("XLS文件清单").[A1].Resize(Did.Count, 1) = WorksheetFunction.Transpose(Did.keys)
TT = Time - T
MsgBox Minute(TT) & "分" & Second(TT) & "秒"
End Sub
import pandas as pdimport os
# 用os.walk遍历文件;用.endswith判断文件后缀
dfs = pd.DataFrame()
for root, dirs, files in os.walk(r'C:\Users\ll\Desktop\pandas\excels'):
for file in files:
if file.endswith('.xlsx'):
# 构建绝对路径
file_name = os.path.join(root, file)
# print(file_name)
df = pd.read_excel(file_name)
# print(df)
dfs = pd.concat([dfs, df])
# print(dfs)
dfs.to_excel(r'C:\Users\ll\Desktop\new.xlsx')
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)