简体   繁体   English

如何正确地将列添加到 Excel 表并使用 VBA 插入公式

[英]How to properly add column to the Excel table and insert a formula using VBA

I would like to be able to add column and insert formula thats looks up for values from a pivot table.我希望能够添加列并插入从 pivot 表中查找值的公式。 'Peer Group Name' is one of the table column. 'Peer Group Name' 是表格列之一。 So far, I'm doing this:到目前为止,我正在这样做:

Set wrk = ThisWorkbook
Set trg_sht = wrk.Worksheets("Peers & Instruments - Overview")
Set tbl = trg_sht.ListObjects("Peers_Instruments_Values")

' Add few additional columns on position 26 & 27
tbl.ListColumns.Add(26).Name = "Median 1Y Return"
tbl.ListColumns.Add(27).Name = "Max 1Y Return"

tbl.ListColumns("Median 1Y Return").DataBodyRange.FormulaR1C1 = "=VLOOKUP([@[Peer Group Name]]," & "'" & CStr(wrk.Worksheets("Peer Group Stats") & "'" & "!C[-25]:C[-22],3,0)")

So the two columns are being added, but the formula doesn't.所以正在添加两列,但公式没有。 Any idea why?知道为什么吗? Is it something do to with wrong column reference?是否与错误的列引用有关?

This looks off:这看起来不对:

CStr(wrk.Worksheets("Peer Group Stats") & "'" & "!C[-25]:C[-22],3,0)")

You don't need a reference to the worksheet, nor CStr .您不需要对工作表的引用,也不需要CStr You just need the worksheet name, which can be hard-coded:您只需要可以硬编码的工作表名称:

tbl.ListColumns("Median 1Y Return").DataBodyRange.FormulaR1C1 = "=VLOOKUP([@[Peer Group Name]],'Peer Group Stats'!C[-25]:C[-22],3,0)"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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