VBA函数用于检查工作簿是否存在

时间:2018-04-04 21:08:46

标签: excel vba excel-vba

我有两个工作簿 1:Source.xlsx 2。 Destination.xlsx 即可。如果#2与#1位于同一位置,则将工作簿返回到我的main函数,否则创建一个新工作簿并返回它。 我有以下代码:

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 

在调试时,该函数返回“Nothing”。我如何让它工作?

1 个答案:

答案 0 :(得分:1)

试试这个 - 无需错误检测:

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
相关问题