以常量作为参数的函数

时间:2019-05-02 09:58:38

标签: vba parameter-passing constants intellisense

某些预定义的VBA方法和函数要求将特定的常量传递给它们,例如:

Application.Calculation = xlCalculationAutomatic
.cells(i,j).End(xlUp).Row
.PpParagraphAlignment = ppAlignCenter

在这些代码段中,常量为 xlCalculationAutomatic xlUp ppAlignCenter

当调用函数/方法并要求填充参数时,VBE Intellisense通常会提供一个有效常量的下拉列表供您选择。

是否可以通过自己的子例程和函数来实现相同的目的?例如。在以下情况下,参数“ sRowOrCol”要求用户当前键入文字“ Row”或“ Col”,但是我想为用户提供一个包含例如“ xlRow”和“ xlCol”。

Function FindLast(ws As Worksheet, sRowOrCol As String, iColRow As Long)
    If sRowOrCol = "Row" Then
        FindLast = ws.Cells(ws.Rows.Count, iColRow).End(xlUp).Row
        Exit Function
    ElseIf sRowOrCol = "Col" Then
        FindLast = ws.Cells(iColRow, ws.Columns.Count).End(xlToLeft).Column
        Exit Function
    Else
        MsgBox "Invalid argument"
    End If    
End Function

2 个答案:

答案 0 :(得分:4)

您似乎正在寻找Enum statement。在您的情况下,可能看起来像这样:

Enum Margin
    Row
    Column
End Enum

' …

Function FindLast(ws As Worksheet, margin As Margin, iColRow As Long)
    If margin = Row Then
    …
End Function

IntelliSense可以与此配合使用,但是您可能想给枚举常量一个通用前缀(例如mar),以便于在IntelliSense DropDown框中选择它们。这就是为什么xlUp的前缀为xl。尽管我个人并不喜欢此类前缀。

答案 1 :(得分:0)

在这种情况下,您也可以使用Excel-Enum XlRowCol:

如果sRow__Col =“ Row” Then

,您似乎也缺少了“或”
Function FindLast(ws As Worksheet, sRowOrCol As XlRowCol, iColRow As Long)
    If sRowOrCol = xlRows Then
        FindLast = ws.Cells(ws.Rows.Count, iColRow).End(xlUp).Row
        Exit Function
    ElseIf sRowOrCol = xlCols Then
        FindLast = ws.Cells(iColRow, ws.Columns.Count).End(xlToLeft).Column
        Exit Function
    Else
        MsgBox "Invalid argument"
    End If
End Function

最初,我只更改了必须更改的部分,以简化OP的操作。调整后的完整代码:

Function FindLast(ws As Worksheet, RowOrCol As XlRowCol, ColRow As Long) As Long
    Select Case RowOrCol
        Case xlRows: FindLast = ws.Cells(ws.Rows.Count, ColRow).End(xlUp).Row
        Case xlColumns: FindLast = ws.Cells(ColRow, ws.Columns.Count).End(xlToLeft).Column
        Case Else: MsgBox "Invalid RowOrCol argument"
    End Select
End Function