VBA中如何打开一个文件夹内的所有EXCEL文件?
展开全部
这段代码是读取一个文件夹下的所有文件,也可以根据扩展名筛选其它格式的.
'有了文件名,就是打开文件,获得每个文件的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 = 1With 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代码添加
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询