我想让我的自定义VBA函数只接受单个单元格的参数。这样做的主要途径是什么:
myCell as Cell
或:
myRange as Range
并得到(如何?)左上角的单元格?答案 0 :(得分:16)
如果您选择多个单元格,该函数将退出:
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
答案 1 :(得分: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
答案 2 :(得分:4)
topLeftValue = myRange.Cells(1, 1).Value
答案 3 :(得分:0)
numRow = myCell.Columns.Count
numCol = myCell.Rows.Count
应该是
numColum = myCell.Columns.Count
numRow = myCell.Rows.Count
答案 4 :(得分:0)
我在自己的函数/子程序中添加了以下范围检查,即使通过了大于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