2013-12-18 29 views
4

我最近試圖在Excel中重新定義Access的Nz(Value, [ValueIfNull])函數,因爲我覺得它非常有用,但它在Excel中不存在(因爲在移動一些有用的函數時發現我感到失望) 。 Access的Nz函數檢查Value - 如果此值爲null,則返回ValueIfNull(否則返回Value)。在訪問它的有用檢查的輸入框中的值(在其他幾件事情):我自己的滾動Nz功能似乎並不難定義可以爲空參數的函數

If Nz(myTextBox.Value, "") = "" Then 
    MsgBox "You need to enter something!" 
End If 

Public Function Nz(value As Variant, Optional valueIfNull As Variant = "") As Variant 
    If IsNull(value) Then 
     Nz = valueIfNull 
    Else 
     Nz = value 
    End If 
End Function 

但只要我嘗試使用任何實際上爲null的東西來調用它,Excel在調用線(Run-time error '91': Object variable or With block not set,我的理解與其他語言中的NullReferenceException大致相同)之前抱怨它,甚至在進入Nz函數體之前。例如,Nz(someObj.Value, "")只有在someObj.Value不爲空(使函數完全無效)時纔有效。

我在這裏錯過了一些VBA的細節嗎?來自像VB.NET這樣的語言,看起來很混亂 - 我理解對象引用只是對存在於內存中的實際對象的地址,所以傳遞引用(而不是對象)不應該引起問題(直到您嘗試實際上當然是對不存在的對象做些什麼)。例如:

Dim myObj As SomeObject 
SomeMethod(myObj) 'the call itself is fine 

Public Sub SomeMethod(SomeObject obj) 
    myObj.DoSomething() 'but *here* it would crash 
End Sub 

如何在VBA中創建接受空參數的subs和函數?

+0

快速注:意識到我可以更多或更少的使用'Iif'而不是複製'Nz'在Excel中,但問題是關於定義一般採用空參數而不是針對特定情況的修復的函數 - 它恰好是一個有用的場景 – Kai

+0

您想與變體或對象一起使用嗎? – 2013-12-18 15:49:35

回答

8

看到thisthat如果有什麼還不清楚,並嘗試

Sub Main() 

    Dim obj As Range 
    Debug.Print Nz(obj) 

    Dim v As Variant 
    v = Null 
    Debug.Print Nz(v) 

End Sub 

Public Function Nz(value As Variant, Optional valueIfNull As Variant = "") As Variant 

    ' deal with an object data type, vbObject = 9 
    If VarType(value) = vbObject Then 
     If value Is Nothing Then 
      Nz = valueIfNull 
     Else 
      Nz = value 
     End If 

    ' deal with variant set to null, vbNull is a Variant set to null 
    ElseIf VarType(value) = vbNull Then 
     If IsNull(value) Then 
      Nz = valueIfNull 
     Else 
      Nz = value 
     End If 
    End If 
End Function 
+1

剛剛發現'沒什麼'以及:)擊敗了我,但這應該是答案:) – oerkelens

+1

+ 1你今天着火:) –

+1

很好的回答,非常有用的鏈接了。謝謝! – Kai

相關問題