12

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

  • 经过myCell as Cell

或者:

  • 默认情况下通过myRange as Range并获取(如何?)左上单元格?
4

5 回答 5

22

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
于 2013-01-23T12:51:39.690 回答
10

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

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
于 2013-01-23T12:28:53.870 回答
4
topLeftValue = myRange.Cells(1, 1).Value
于 2013-01-23T12:36:37.990 回答
1

我在我自己的函数/子程序中添加了以下范围检查,以便即使通过了 > 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
于 2018-10-24T18:51:44.267 回答
0
numRow = myCell.Columns.Count 

numCol = myCell.Rows.Count 

应该

numColum = myCell.Columns.Count 

numRow = myCell.Rows.Count  
于 2015-03-12T09:11:47.677 回答