打开excel工作簿是否有最佳做法?我有这个功能
Function openWorkbook(workbookpath As String, Optional worksheetname As String)
If IsMissing(worksheetname) Then worksheetname = "Sheet1"
'Test workbookpath
Dim wb As Workbook
Dim ws As Worksheet
Dim fso As Scripting.FileSystemObject
Dim wbname As String
wbname = fso.GetFileName(workbookpath)
Dim thisIsSoStupid As Boolean
thisIsSoStupid = True
'test if workbook is open
For Each wb In Workbooks
If wb.Name = wbname Then
Set openWorkbook = wb
thisIsSoStupid = False
break
End If
Next
If thisIsSoStupid And Dir(workbookpath) <> 0 Then
openWorkbook = Workbooks.Open(workbookpath)
Else
openWorkbook = False
End If
End Function
我想要g = openWorkBook(path)||false
这样的javascript快捷方式或$g = fopen($path, 'w')
或die('bugger');
,但当然,如果找不到该文件,如果我的代码期望一个对象,它将返回false并且我无法评估false。
我是否必须在错误恢复,然后捕获错误?我讨厌愚蠢的错误废话。这是对意大利面条代码的邀请
答案 0 :(得分:3)
您的函数未声明返回类型,因此隐式Variant
。
失败时返回布尔值False
,成功时返回Workbook
对象引用。这使得客户端代码更难以编写。
相反,让函数返回Workbook
引用,并在失败时返回Nothing
。
此外,如果您在签名中提供可选参数的默认值,那么您的IsMissing
检查将变得多余。
现在,当您担心打开工作簿时,我不确定为什么您需要工作表名称 - 特别是因为,好吧,你不是使用worksheetname
参数执行任何操作。语言中的异常前错误处理不是唯一负责意大利面条代码的事情。
这是一个更理智的版本:
Public Function OpenWorkbook(ByVal path As String) As Workbook
On Error GoTo CleanFail
Dim result As Workbook
If Not IsWorkbookOpen(path, result) Then
Set result = Application.Workbooks.Open(path)
End If
CleanExit:
Set OpenWorkbook = result
Exit Function
CleanFail:
Set result = Nothing
Resume CleanExit
End Function
Public Function IsWorkbookOpen(ByVal path As String, Optional ByRef outWorkbook As Workbook = Nothing) As Boolean
Dim book As Workbook
For Each book In Application.Workbooks
If book.FullName = path Then
IsWorkbookOpen = True
Set outWorkbook = book
Exit For
End If
Next
End Function
注意:
Public
访问修饰符ByVal
修饰符;您的代码隐式传递参数ByRef
,但不需要。PascalCase
名称,以符合每个现有VBA API的命名方式ByRef
修饰符out
前缀表示“out”参数这些不是“最佳实践”,它们就是我写VBA的方式。我很确定在您的代码中将thisIsSoStupid
作为变量名称通常被视为非专业代码。
对“愚蠢错误废话”的反应很好(我更倾向于处理异常),但是当你的代码有未使用的参数,模糊的返回类型和不良的命名时就不行了。