excel - 浏览它们时如何使用获取列数据?
问题描述
我有多张纸,每张只有 1 张不同宽度和高度的桌子。
我正在尝试实现:一旦用户通过组合框选择了工作表(这有效),我就可以在该工作表上列出表中的标题。
我可能的解决方案想法:我的想法是在用户表单的组合框中列出表头。
- 我计算所选工作表上的列,工作
- for 循环遍历列以从每个列中获取标题名称并堆叠到 combobox.list 中,
代码:
Private Sub chcSite_Change()
Dim siteSheet As String
siteSheet = WorksheetFunction.VLookup(Me.chcSite.Value, Worksheets("Overview").Range("SiteTable"), 2, False)
Me.chcRange.Enabled = True ' enables combobox for headers list
Dim COLS As Integer
COLS = Worksheets(siteSheet).ListObjects(1).ListColumns.Count
Dim i As Integer
i = 1
For i = 1 To COLS
If Worksheets(siteSheet).Cells(Columns(i), 1) = "" Then Exit For ' if header is empty = also end of table cols.
MsgBox Worksheets(siteSheet).Cells(Columns(i), 1) ' debug to see what it returns.
Next i
'Me.chcRange.List = Worksheets(siteSheet).ListObjects(1).ColumnHeads ' random test of columnheads
End Sub
如您所见,我期望 Worksheets(siteSheet).Cells(Columns(i), 1) 返回一些东西,但它似乎只是一个指针/选择器。
解决方案
You might benefit from reading The VBA Guide To ListObject Excel Tables.
For example to get the 3rd heading of a table use
.ListObjects("Table1").HeaderRowRange(3)
The ListObject has its own row/column numbering and may be different from the sheets row/column numbering.
It should look something like this:
Dim i As Long 'always use Long
'i = 1 not needed
For i = 1 To COLS
' v-- this part is not needed …
If Worksheets(siteSheet).ListObjects(1).HeaderRowRange(i) = "" Then
Exit For ' if header is empty = also end of table cols.
End If
' ^-- … because headers of ListObjects can not be empty by definition.
' And HeaderRowRange can only access the headers of the ListObjects.
MsgBox Worksheets(siteSheet).ListObjects(1).HeaderRowRange(i) ' debug to see what it returns.
Next i
So you can shorten it to:
Dim i As Long
For i = 1 To COLS
MsgBox Worksheets(siteSheet).ListObjects(1).HeaderRowRange(i) ' debug to see what it returns.
Next i
Note that Cells(Columns(i), 1)
could not work because eg Columns(2)
references the complete column B (it is a range representing the full column 2) and Cells
needs a row/column number like Cells(row, column)
.
推荐阅读
- python - 为什么 Binary_Cross-entropy Loss 给出负值?
- terraform-provider-azure - 如何使用 terraform 将虚拟网络添加到 api 管理?
- javascript - 转换嵌套对象中的所有值
- sql - 为 azure 突触分析创建外部表的问题
- java - installCert.java 中的 SavingTrustManager 函数什么时候调用?
- javascript - Javascript RegExp 未知的重复匹配
- php - 试图从json数组将列数据插入mysql
- python - 将各种对象信息保存在易于访问的位置
- python - numpy.dot 函数矩阵乘法:Numpy 将 AxB 矩阵和 1xB 矩阵相乘为 AxB 矩阵和 Bx1 矩阵
- entity-framework-core - 在 Entity Framework Core 中重用包含语句