How do I reference an Excel ListObject table column if the column name has line breaks?

给你一囗甜甜゛ 提交于 2020-01-25 23:00:11

问题


I'm tasked with the following:

  • several sheets from different workbooks have to be copied to a new workbook
  • each of those sheets contains an Excel table (a ListObject), named like the sheet with a postfixed T (sheet Foo, table: FooT)
  • the new workbook has to contain a summary sheet where each table name is listed, and various values of the respective tables are presented by referencing them with suitable formulas

This has to be done frequently for different workbooks, so the idea was to do this in VBA.

Copying the sheets is easy, listing the table names in a new sheet is easy, but referencing the values runs into problems.

The general idea is to do the following

ActiveSheet.Range("A1").Value = "FooT"
ActiveSheet.Range("B1").Formula = "=FooT[[#Totals],[Quantity]]"
ActiveSheet.Range("C1").Formula = "=FooT[[#Totals],[Total List Price]]"

and iterate over all sheets.

Setting the value for A and the formula for B works as expected and gets the expected results.

The issue with C is that instead of "Total List Price", the column header is actually formatted as

"Total
List
Price"

I can't change that, this has been a design decision.

This is also how the column name shows up in the formula if I add the formula to the cell manually.

So there's some sort of line break happening here, and I've tried cater to this in VBA with

ActiveSheet.Range("C1").Formula = "=FooT[[#Totals],[Total" & vbCrLf & _
                                                   "List" & vbCrLf & _
                                                   "Price]]"

and vb_Cr and vb_Lf and vb_Newline instead of the vbCrLf. Trying to set C's formula to any of these variations yields the infamous Error 1004.

Getting the value of the column header from one of the sheets and using it in the formula works. This could be a potential workaround, but I'd really like to know what I'm missing or how I can figure out how to build this formula string correctly.


回答1:


Your formula is OK but typically, the newline character will be vbLf if the title was set from the keyboard. I also suspect there might be leading and/or trailing space characters anywhere in the title. Select your title cell and, from the VBE's Immediate Window (Ctrl+G), type Debug.Print ActiveCell.Value, then check where each printed line ends.

Are you using Option Explicit? In your question, you mention you've tried vb_Lf but this constant doesn't exist and, without Option Explicit, would have been interpreted as an empty string.



来源:https://stackoverflow.com/questions/46941828/how-do-i-reference-an-excel-listobject-table-column-if-the-column-name-has-line

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