简体   繁体   中英

Excel VBA referencing string in Formula Array

Need help inserting string into formula array to bypass the 255 character limit.

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

I've tried double-quotes ("" & ref3 & "") and double-double-quotes ("""" & ref3 & """") and I keep getting an application-defined or object-defined error. I feel like this is an easy fix, but I can't seem to figure it out. Any help would be appreciated. Thanks!

You can't get around a property's character limit by setting the string in VBA instead of through the UI.

If the length of your string is truly beyond 255-characters, it will continue to fail. As an alternative, you may control the length of the formula better if you use the Names manager to define a named range pointing to your external workbook , and reference that range in your formula. Ie:

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

I also agree with JohnRC's comments above - be precise and qualify your references to aid in debugging.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM