none
Object variable or With block variable not set RRS feed

  • Question

  • Hi

    I have code as below;

    Function getOption(OptionPara As Long)
    Dim x
     
      getOption = Nothing
    
    End Function

    Problem is I am getting 'Object variable or With block variable not set' error on the line getOption = Nothing

    What am I doing wrong? 

    Thanks

    Regards

    Wednesday, July 26, 2017 12:02 PM

Answers

  • Nothing can only be used for object variables. Your function returns (implicitly) a variant. And as object variable it must be used properly to handle that case.

    1. Declare always your variables and return types explicitly.

    2. Use explicit visibility modifier.

    3. Assigning a value to a object variable requires the Set keyword.

    Option Compare Database
    Option Explicit
    
    Public Function getOption(OptionPara As Long) As Object
    
      Set getOption = Nothing
    
    End Function
    
    Public Sub TestGetOption()
     
      Dim o As Object
      
      Set o = getOption(123)
      If o Is Nothing Then
        MsgBox "Nothing"
      Else
        MsgBox "D'oh."
      End If
      
    End Sub

    Wednesday, July 26, 2017 12:54 PM

All replies

  • Hi, I think Nothing is for objects but you're using it on a function. Try: getOption = Null
    Wednesday, July 26, 2017 12:43 PM
  • Nothing can only be used for object variables. Your function returns (implicitly) a variant. And as object variable it must be used properly to handle that case.

    1. Declare always your variables and return types explicitly.

    2. Use explicit visibility modifier.

    3. Assigning a value to a object variable requires the Set keyword.

    Option Compare Database
    Option Explicit
    
    Public Function getOption(OptionPara As Long) As Object
    
      Set getOption = Nothing
    
    End Function
    
    Public Sub TestGetOption()
     
      Dim o As Object
      
      Set o = getOption(123)
      If o Is Nothing Then
        MsgBox "Nothing"
      Else
        MsgBox "D'oh."
      End If
      
    End Sub

    Wednesday, July 26, 2017 12:54 PM