Visual Basic表对象:获取特定行的列数

时间:2018-02-09 17:23:29

标签: vba excel-vba excel

我正在尝试将表格中的值从word文档复制到Excel工作表。我被困在读取每行不同列数的表中的值。例如。第2行有3列,但第1行只有2列。因此.Rows(1).Columns.Count为3并导致

  

索引越界

在第1排。

我认为它应该是这样的:Set wdDoc = GetObject(wdFileName) ' (path to .docx) With wdDoc TableNo = wdDoc.tables.Count If TableNo = 0 Then MsgBox "Word-Dokument enthält keine Tabellen", vbExclamation End If ' Loop through all tables For iTable = 1 To TableNo With .tables(iTable) ' Check if table contains correct headlines Dim columnsNo As Integer 'columnsNo = .Rows(1).Columns.Count ' this it should be but doesnt exist For iCol = 1 To .Columns.Count ' this Count returns 3 although 1st row has only 2 columns If (.cell(1, iCol) = sAlias) Then containsAlias = True End If Next iCol End With Next iTable End With Set wdDoc = Nothing

但我无法在在线文档或论坛中找到任何内容。

这是(精简的)代码:

5

我希望代码足够清晰,粘贴到stackoverflow上以填充空白区域。谢谢你的帮助。

1 个答案:

答案 0 :(得分:0)

在另一天再看一遍之后,我自己找到了解决方案。要从Table object (Word)获取特定行中的列数(=单元格数),您可以使用

.Rows(1).Cells.Count

现在我发现它似乎非常明显。