2015-10-21 48 views
0

我想檢測是否通過了opational參數,但由於某些原因,所有常用函數(IsMissing()/ IsEmpty()/ IsNull())總是返回false。如何檢測何時可選的ByRef參數未通過

這就是我想:

Public Sub SetValue(Key As String, Optional ByRef ws As Worksheet) 
    If IsMissing(ws) Or IsEmpty(ws) Or IsNull(ws) Then 
     ws = ThisWorkbook.Sheets(SheetName) 
    End If 

我也嘗試設置WS爲Nothing或Null,但結果是一樣的:

Public Sub SetValue(Key As String, Optional ByRef ws As Worksheet = Nothing) 
    If IsMissing(ws) Or IsEmpty(ws) Or IsNull(ws) Then 
     ws = ThisWorkbook.Sheets(SheetName) 
    End If 

任何想法,爲什麼這可能是happenning ?

回答

2

嘗試is nothing

Private Sub CommandButton1_Click() 
    Dim ws As Excel.Worksheet 
    Set ws = ActiveWorkbook.Sheets("sheet1") 

    'Call the sub both ways. 
    SetValue "a" 
    SetValue "a", ws 
End sub 

Public Sub SetValue(Key As String, Optional ByRef ws As Worksheet) 
    If ws Is Nothing Then 
     'We got a sheet 
     MsgBox "We got no sheet" 
    End If 

    If Not ws Is Nothing Then 
     'We got a sheet 
     MsgBox ws.name 
     MsgBox "We got a sheet" 
    End If 
End sub 
1

建設是任何方法都行不通。我在所有參數中都使用它。

Public Sub SetValue(ByRef Key As String, _ 
        Optional ByRef ws As Worksheet = Nothing) 

    'Make sure we have the object 
    If ws Is Nothing Then 
     Set ws = ThisWorkbook.Sheets(SheetName) 
    End If 

End Sub 

希望這有助於。 :)

+0

+1因爲這個答案比較好,以後不能用空ws工作。我平時默認將它設置爲'activesheet'用於子/功能應該在任何地方工作。 –

+0

同樣在這裏帕特里克我總是將我的可選工作表設置爲Activesheet,我確保它可以在任何地方工作。 –