Excel VBA引用公式数组中的字符串

时间:2018-01-21 18:43:32

标签: arrays excel string vba excel-vba

需要帮助将字符串插入公式数组以绕过255个字符的限制。

Sub FindCAHS()

Dim HS As Range
Dim refworkbook As Variant
Dim ref1 As Workbook
Dim ref2 As Worksheet
Dim ref3 As String
Dim lastRow As Long


    refworkbook = Application.GetOpenFilename(".xlsx Files (*.xlsx), *.xlsx", 1, "Select the HS Reference xlsx")
    If refworkbook = False Then Exit Sub

    Set HS = Range("J2")
    Set ref1 = Workbooks.Open(refworkbook)
    Set ref2 = ref1.Worksheets.Item(2)

    lastRow = Sheet1.Range("D" & Rows.Count).End(xlUp).Row

        For j = 2 To lastRow
            If IsEmpty(Cells(j, 10).Value) = True Then
                 ref3 = "'" & ref1.Path & Application.PathSeparator & _
                 "[" & ref1.Name & "]" & ref2.Name & "'"
                HS.Offset(j - 2, 0).FormulaArray = _
                "=vlookup($F$" & j & "&$G$" & j & "&$H$" & j & ",Choose({1,2},""" & ref3 & """!$C:$C&ref3!$D:$D&""" & ref3 & """!$E:$E,""" & ref3 & """!$F2:$F5000),2,0)"
                Else: Exit Sub
            End If
        Next

    ref1.Close False
End Sub

我尝试过双引号(""& ref3&"")和双引号("" ""& ref3&"""")并且我不断收到应用程序定义或对象定义的错误。我觉得这很容易解决,但我似乎无法解决这个问题。任何帮助,将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:0)

通过在VBA中而不是通过UI设置字符串,您无法绕过property's character limit

如果字符串的长度真的超过255个字符,它将继续失败。作为替代方案,如果使用名称管理器定义named range pointing to your external workbook并在公式中引用该范围,则可以更好地控制公式的长度。即:

ActiveWorkbook.Names.Add Name:="MyRange", RefersTo:=Rng1 

我也同意JohnRC上面的评论 - 准确并确定您的参考资料以帮助调试。