I want to make my custom VBA function accept only a single-cell argument. What is the rightway of doing it:
- pass
myCell as Cell
or:
- pass
myRange as Rangeand get (how?) the left-upper cell by default?
If you select more than one cell the function will exit:
Function AcceptOneCell(rng As Range)
If (rng.Cells.Count > 1) Then
AcceptOneCell = "Only allow 1 cell"
Exit Function
End If
' your code here
End Function
Assuming your user will enter a range with multiple columns and rows, you can do the following check to exit the function if that's what you meant in the question...
Function myFunction(ByRef myCell as Range) as SomeDataType_of_your_choice
Dim numRow as Long, numCol as Long
numRow = myCell.Columns.Count
numCol = myCell.Rows.Count
If numRow > 1 or numCol > 1 Then
MsgBox "Only one cell is accepted"
Exit Function
Else
'-- do other stuff you want to do here
End If
End Function
I've added the below range checks within my own functions/subs, in order to proceed even if a range of > 1 cell is passed. This forces the selection of the top-left-most cell in the case a range with multiple cells is passed to the function. This is an alternative path to the other answers, which end the current function instead.
Sub DoSomethingWithCells(StartCell As Range)
'Ensure that only the first cell of range is selected
If (StartCell.Cells.Count > 1) Then
'Select only the first cell
StartCell = StartCell.Cells(1, 1).Address
End If
'Do whatever you need to do here
End Sub
Myfunction(ByRef myCell as Range)as the parametertopLeftValue = myRange.Cells(1, 1).Valuedefaultpart though, if you had emphasized that you want to take first cell of any range then yes, would have been clearer.