Consulting

Results 1 to 4 of 4

Thread: Optional argument in a function error

  1. #1

    Optional argument in a function error

    I'm trying to write a function to retrieve last used cell, but get "Object variable or with block not defined" error...

    [VBA]Function GetLastCell(Optional my_sheet As Worksheet)
    Dim Cell As Integer

    If IsEmpty(my_sheet) Then
    GetLastCell = ActiveSheet.UsedRange.Rows.Count
    Else
    GetLastCell = my_sheet.UsedRange.Rows.Count
    End If

    End Function[/VBA]

    This is what I use to test it:
    [VBA]Sub test3()
    MsgBox GetLastCell()
    End Sub[/VBA]

    It works well if I define the argument in the function, but screws me with default value, can anyone help?

  2. #2
    VBAX Expert Tinbendr's Avatar
    Joined
    Jun 2005
    Location
    North Central Mississippi (The Pines)
    Posts
    993
    Location
    My_Sheet can't be optional. You'll have to pass it to be able to use it in the function.

  3. #3
    Thanks, it works.

  4. #4
    Mac Moderator VBAX Guru mikerickson's Avatar
    Joined
    May 2007
    Location
    Davis CA
    Posts
    2,778
    To test if an optional function argument has been passed, one should either use a Variant argument and use IsMissing or should test the argument against a null.
    [VBA]Function GetLastCell(Optional my_sheet As Worksheet)
    Dim Cell As Integer

    If my_sheet Is Nothing Then
    GetLastCell = ActiveSheet.UsedRange.Rows.Count
    Else
    GetLastCell = my_sheet.UsedRange.Rows.Count
    End If

    End Function[/VBA]

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •