Tuesday, December 1, 2009

Function that returns value in VBA

To code a function that returns value to the calling sub, use FunctionName as the VariableName in the function.

e.g.
function findrownbr()
findrownbr=10
end function

sub readCellData ()
cell_nbr = findrownbr()
msgbox Range("A" &cell_nbr)
end sub

1 comment:

  1. Your code does not declare any variables. This is bad practice. You should explicitly declare the return type of the function, and declare the holding variable to be of the same type. i.e.

    Function findrownbr() As Integer
    findrownbr = 10
    End Function

    Sub readCellData()
    Dim cell_nbr As Integer
    cell_nbr = findrownbr
    MsgBox Range("A" & cell_nbr)
    End Sub

    ReplyDelete