VBA功能以检查工作簿是否存在



我有两个工作簿 1:source.xlsx 2。destination.xlsx 。如果#2与#1相同的位置存在,则将工作簿返回我的主要功能,否则创建一个新的工作簿并将其返回。我有以下代码:

Function CheckForExistingWorkbooks() As Workbook
Dim wb1 As Workbook
Dim FilePath As String
Dim TestStr As String
FilePath = ThisWorkbook.Path & "Student Information.xlsx"
TestStr = ""
On Error Resume Next
TestStr = Dir(FilePath)
On Error GoTo 0
If TestStr = "" Then
    Set wb1 = Workbooks.Add
Else
    Set wb1 = Workbooks.Open(FilePath)
End If
CheckForExistingWorkbooks = wb1
End Function 

在调试时,功能返回"无"。我该如何工作?

尝试一下 - 无需错误检测:

Function CheckForExistingWorkbooks() As Workbook
    Dim wb1 as Workbook
    Dim TestStr As String, FilePath As String
    FilePath = ThisWorkbook.Path & "Student Information.xlsx"
    If Len(Dir(FilePath)) = 0 Then
        Set wb1 = Workbooks.Add
    Else
        Set wb1 = Workbooks.Open(FilePath)
    End If
    Set CheckForExistingWorkbooks = wb1
End Function

最新更新