我有两个工作簿 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”。我如何让它工作?
答案 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