我正在创建一个程序,它从一长串文件中打开指定文件路径中的文件。它们都具有相同的名称格式,但它们并非都是.xlsx文件格式,有些是.xlsm格式。
For file = 2 To 200
If RefSheet.Cells(file, 1) = "" Then Exit For 'no more data, end now
If KeepOpen Then
'continue as is, because already open
Else
Set InBook = Workbooks.Open(Filename:=RefSheet.Cells(file, 1) & RefSheet.Cells(file, 2), UpdateLinks:=False, ReadOnly:=True)
End if
End If
我正在尝试进行一个简单的测试,在尝试打开之前首先为.xlsx / .xlsm发送文本名称,但似乎无法使其正确。
已尝试进行错误处理,但无法按预期执行
答案 0 :(得分:0)
从
更改您的代码Set InBook = Workbooks.Open(Filename:=RefSheet.Cells(file, 1) & RefSheet.Cells(file, 2), UpdateLinks:=False, ReadOnly:=True)
到
Dim fName As String
If Dir(RefSheet.Cells(file, 1) & RefSheet.Cells(file, 2))<>"" Then
fName = RefSheet.Cells(file, 1) & RefSheet.Cells(file, 2)
ElseIf Dir(RefSheet.Cells(file, 1) & RefSheet.Cells(file, 2) & ".xlsm")<>"" Then
fName = RefSheet.Cells(file, 1) & RefSheet.Cells(file, 2) & ".xlsm"
Else
fName = RefSheet.Cells(file, 1) & RefSheet.Cells(file, 2) & ".xlsx"
End If
Set InBook = Workbooks.Open(Filename:=fName, UpdateLinks:=False, ReadOnly:=True)
这将首先测试文件名是否与B列中记录的完全一样有效。如果不是,它将查看是否存在具有“xlsm”扩展名的文件,如果存在,则使用它。否则,它将假定文件具有“xlsx”扩展名。
另一种方法(可能也适用于csv和txt文件)将是:
Dim fName As String
'The Dir command will just return the filename.extension portion of the first file that matches the specification
fName = Dir(RefSheet.Cells(file, 1) & RefSheet.Cells(file, 2) & ".*")
If fName = "" Then
'No matching file was found
MsgBox "File requested (" & RefSheet.Cells(file, 1) & RefSheet.Cells(file, 2) & ") does not exist"
Else
'Concatenate the path and filename.extension together and open the file
Set InBook = Workbooks.Open(Filename:=RefSheet.Cells(file, 1) & fName, UpdateLinks:=False, ReadOnly:=True)
End If
P.S。如果您希望预先完成所有声明,则可以将fName的声明移动到Sub(或Function)的开头。