Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VBA函数检查工作簿是否存在_Vba_Excel - Fatal编程技术网

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

VBA函数检查工作簿是否存在,vba,excel,Vba,Excel,我有两本工作手册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 & "\Stude

我有两本工作手册1:Source.xlsx2。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 

调试时,函数返回“Nothing”。如何使其工作?

尝试此方法-无需错误检测:

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

使用Set-CheckForExistingWorkbook=wb1