Excel/VBA:传递单个单元格作为参数

use*_*686 10 excel vba excel-vba

我想让我的自定义VBA函数只接受单单元格参数.这样做的正确方法是什么:

  • 通过 myCell as Cell

要么:

  • myRange as Range默认情况下传递并获取(如何?)左上角的单元格?

InC*_*ext 18

如果您选择多个单元格,该函数将退出:

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
Run Code Online (Sandbox Code Playgroud)


bon*_*igo 8

假设您的用户将输入具有多个列和行的范围,您可以执行以下检查以退出该函数,如果这是您在问题中的意思...

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
Run Code Online (Sandbox Code Playgroud)