我想让我的自定义 VBA 函数只接受一个单元格参数。这样做的正确方法是什么:
- 经过
myCell as Cell
或者:
- 默认情况下通过
myRange as Range
并获取(如何?)左上单元格?
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
假设您的用户将输入一个包含多列和多行的范围,如果这是您在问题中的意思,您可以执行以下检查以退出该函数...
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
topLeftValue = myRange.Cells(1, 1).Value
我在我自己的函数/子程序中添加了以下范围检查,以便即使通过了 > 1 个单元格的范围也可以继续。如果将具有多个单元格的范围传递给函数,这将强制选择最左上角的单元格。这是其他答案的替代路径,而是结束当前功能。
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
numRow = myCell.Columns.Count
numCol = myCell.Rows.Count
应该
numColum = myCell.Columns.Count
numRow = myCell.Rows.Count