将自定义公式添加到Range()单元格

时间:2018-04-18 16:56:23

标签: vba excel-vba excel-formula excel

    Sub test()
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False 'keeping the screen clean

    Sheets("Data").Select



'Here is where the error is triggered.
    With ThisWorkbook.Worksheets("TestSheet")
        '.Range("A2:A" & Lr).Formula = "=CusVlookup(Z2,Data'!A:B,2)" <- this doesnt work either
        .Range("A2:A" & Lr) = "=CusVlookup(Z2,Data'!A:B,2)"
    End With

    End Sub


Function CusVlookup(lookupval, LookupRange As Range, indexcol As Long)
    Dim x As Range
    Dim Result As String
    Result = ""
    For Each x In LookupRange
        If x = lookupval Then
            Result = Result & "," & x.Offset(0, indexcol - 1)
        End If
    Next x
    CusVlookup = Result
End Function

我尝试使用常规Vlookup并且工作得很好,但如果我尝试使用此自定义函数,则会触发错误。顺便说一下,我需要获得多个匹配&#34; vlookups&#34;用逗号分隔的一个单元格。(我添加了目标,以防万一你知道一个更好/更快的方法来做同样的事情。)

代码有什么问题?

  

错误1004 - 应用程序定义或对象定义的错误

0 个答案:

没有答案