用VBA循环打开指定文件夹中的各个EXCEL,执行对应的宏操作后关闭。期间一直报找不到文件。
代码执行到SetmyFile=FSO.GetFile(CStr(varFileList(l)))就报文件未找到,是文件后缀的问题吗?PrivateSubCommandBu...
代码执行到Set myFile = FSO.GetFile(CStr(varFileList(l))) 就报文件未找到,是文件后缀的问题吗?
Private Sub CommandButton1_Click()
Dim strFolder As String
Dim varFileList As Variant
Dim FSO As Object, myFile As Object
Dim myResults As Variant
Dim l As Long
'显示打开文件夹对话框
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then Exit Sub '未选择文件夹
strFolder = .SelectedItems(1)
End With
'获取文件夹中的所有文件列表
varFileList = fcnGetFileList(strFolder)
If Not IsArray(varFileList) Then
MsgBox "未找到文件", vbInformation
Exit Sub
End If
'获取文件的详细信息,并放到数组中
ReDim myResults(0 To UBound(varFileList) + 1, 0 To 5)
myResults(0, 0) = "文件名"
Set FSO = CreateObject("Scripting.FileSystemObject")
For l = 0 To UBound(varFileList)
Set myFile = FSO.GetFile(CStr(varFileList(l)))
myResults(l + 1, 0) = CStr(varFileList(l))
Workbooks.Open (myResults(l + 1, 0))
Workbooks(myResults(l + 1, 0)).Activate
ActiveWorkbook.Close False
Next l
Set myFile = Nothing
Set FSO = Nothing
Application.Quit
End Sub 展开
Private Sub CommandButton1_Click()
Dim strFolder As String
Dim varFileList As Variant
Dim FSO As Object, myFile As Object
Dim myResults As Variant
Dim l As Long
'显示打开文件夹对话框
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then Exit Sub '未选择文件夹
strFolder = .SelectedItems(1)
End With
'获取文件夹中的所有文件列表
varFileList = fcnGetFileList(strFolder)
If Not IsArray(varFileList) Then
MsgBox "未找到文件", vbInformation
Exit Sub
End If
'获取文件的详细信息,并放到数组中
ReDim myResults(0 To UBound(varFileList) + 1, 0 To 5)
myResults(0, 0) = "文件名"
Set FSO = CreateObject("Scripting.FileSystemObject")
For l = 0 To UBound(varFileList)
Set myFile = FSO.GetFile(CStr(varFileList(l)))
myResults(l + 1, 0) = CStr(varFileList(l))
Workbooks.Open (myResults(l + 1, 0))
Workbooks(myResults(l + 1, 0)).Activate
ActiveWorkbook.Close False
Next l
Set myFile = Nothing
Set FSO = Nothing
Application.Quit
End Sub 展开
1个回答
追问
你好,在Set myFile前用你的方法msgbox CStr(varFileList(l)) 先查看了,得出的结果就是等于文件的名称的。但是用Set myFile = FSO.GetFile(CStr(varFileList(l))) 但是到这串代码,又报文件未找到。是这个代码的问题吗?Set myFile = FSO.GetFile () 括号中只找到了文件名,需要指定到详细路径吗?
追答
文件名可以重名的千千万 你不写具体是哪个文件夹 程序只能默认找同目录下的
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询