VBA函数检查工作簿是否存在
我有两本工作手册1:Source.xlsx和2。Destination.xlsx。如果#2与#1位于同一位置,则将工作簿返回到我的主函数,否则创建一个新工作簿并返回它。 我有以下代码: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
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