VBA对象需要excel.range错误

时间:2016-10-17 08:12:16

标签: excel vba excel-vba vb6

我试图为vba查找公式创建一个函数,就像这样。

 Private Function setVlookUp(Optional startingRow As Long, _
                   Optional endingRow As Long, _
                   Optional column As Long, _
                   Optional lookup_value_col As Long, _
                   Optional table_Array As String, _
                   Optional ByRef table_Array_FirstCell As Excel.Range, _
                   Optional table_Array_SecondCell As Excel.Constants, _
                   Optional col_num As Long, _
                   Optional range_lookup As Long, _
                   Optional isSetNumberFormat As Boolean = False, _
                   Optional NumberFormat As String)

    Dim rowCounter As Long
    With mWorksheet
        For rowCounter = startingRow To endingRow
                .Cells(rowCounter, column).Value = "=VLOOKUP(" & .Cells(rowCounter, lookup_value_col).Address(False, False) & ",'" & table_Array & "'!" & table_Array_FirstCell & ":" & table_Array_SecondCell & "," & col_num & "," & range_lookup & ")"
        Next rowCounter
    End With

这就是我调用函数

 Call setVlookUp(4, rowEnd, 4, 3, mArraySheetName(sheetCounter - 1, 0), .Cells(6, mArrayIntLocation(0, 0)).Address(False, False))

但是有一个错误表示"对象需要"。我无法找到问题。

1 个答案:

答案 0 :(得分:2)

当Function / Sub需要一个范围时,你正在传递一个字符串。

.Cells(6, mArrayIntLocation(0, 0)).Address(False, False)

这将以字符串形式返回地址(例如字符串"A6")。要获得范围,只需删除.Address并使用

即可
.Cells(6, mArrayIntLocation(0, 0))

当处理(这么多)参数时,尤其是使用可选参数时,我总是在函数调用中指定参数以保持其可读性,例如。

Call setVlookUp(startingRow:=4, _
                endingRow:=rowEnd, _
                ...
                )