用VBA循环打开指定文件夹中的各个EXCEL,执行对应的宏操作后关闭。期间一直报找不到文件。

代码执行到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

那肯定就是文件路径不对喽 你完全可以msgbox CStr(varFileList(l)) 来看看这个变量具体是什么内容 核对下就清楚了

追问

你好,在Set myFile前用你的方法msgbox CStr(varFileList(l)) 先查看了,得出的结果就是等于文件的名称的。但是用Set myFile = FSO.GetFile(CStr(varFileList(l))) 但是到这串代码,又报文件未找到。是这个代码的问题吗?Set myFile = FSO.GetFile () 括号中只找到了文件名,需要指定到详细路径吗?

追答

文件名可以重名的千千万 你不写具体是哪个文件夹 程序只能默认找同目录下的

温馨提示:答案为网友推荐,仅供参考

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网