Create dynamic named range in VBA that references ListObjects table

喜欢而已 提交于 2020-01-16 06:46:29

问题


I need to create a named range that refers to the last few rows of data in a ListObject table. While I can do it manually from the ribbon (Formulas > Define Name) I have to do this across 20 sheets with 3 ranges each.

When I try this using VBA I get error 1004 and a warning that there's a problem with the formula and to remove the "=" if I'm not trying to enter a formula. Any ideas how to resolve this?

Open a fresh Sheet1 to try my code. It'll create a ListObjects table and will try to create the Named range.

Sub test2()
    Dim wks As Worksheet, tbl As ListObject
    Dim arr()

    arr = [{"Date","1/1/2016","2/1/2016","3/1/2016","4/1/2016";"Green",100,200,300,400;"Yellow",350,250,150,50;"Red",10,7,5,3}]
    Set wks = ActiveSheet
    wks.Range("a1:d5") = WorksheetFunction.Transpose(arr)

    Set tbl = wks.ListObjects.Add(xlSrcRange, wks.Range("a1").CurrentRegion, , xlYes)
    tbl.Name = "tblTix"

    ActiveWorkbook.Names.Add "rngRedLast3Mos", "=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],1)-3,MATCH(""Red"",tblTix[#Headers],0)-1,3,1)"  'THIS FAILS
    ActiveWorkbook.Names.Add "rngRedLast3Mos", "=OFFSET(Sheet1!$A$1,2,3,3,1)"  'THIS WORKS
    ActiveWorkbook.Names.Add "rngRedLast3Mos", "=Sheet1!$D$3:$D$5"  'THIS ALSO WORKS

    Debug.Print ActiveWorkbook.Names("rngRedLast3Mos").RefersTo
    Debug.Print ActiveSheet.Range("rngRedLast3Mos").Address

End Sub

If I manually define the range in Name Manager, I can assign this reference, and it works:

=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],1)-3,MATCH("Red",tblTix[#Headers],0)-1,1,1)

I don't understand what's going wrong.


回答1:


Change

ActiveWorkbook.Names.Add "rngRedLast3Mos", _
"=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],1)-3,MATCH(""Red"",tblTix[#Headers],0)-1,3,1)"

to

ActiveWorkbook.Names.Add Name:="rngRedLast3Mos", RefersToR1C1:= _
"=OFFSET(tblTix,MATCH(MAX(tblTix[Date]),tblTix[Date],1)-3,MATCH(""Red"",tblTix[#Headers],0)-1,3,1)"

Do that for the rest as well



来源:https://stackoverflow.com/questions/38780176/create-dynamic-named-range-in-vba-that-references-listobjects-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!