如何用ExcelVBA遍历行列不等的word表?

pod7payv  于 2023-03-24  发布在  其他
关注(0)|答案(3)|浏览(124)

我试图导入一个Word表格在Excel中使用VBA。我有一些代码,但我有一个问题,通过表迭代,因为它有不平等的行和列。
下面是我的代码:

Sub ImportWordTable()
    
    Dim wdDoc As Object
    Dim wdTable As Object
    Dim Word_Document_Name As Variant
    Dim TableNo As Integer
    Dim TableIndex As Integer    

    Word_Document_Name = Application.GetOpenFilename("Word files,*.doc;*.docx", , "Browse for Word File")

    If Word_Document_Name = False Then Exit Sub 'In case user hit the cancel button

    Set wdDoc = GetObject(Word_Document_Name) 'open Word file (Step takes time to open Word Document and inspect)

    With wdDoc

    TableNo = wdDoc.Tables.Count

    If TableNo = 0 Then MsgBox "This document contains no tables": Exit Sub

    For TableIndex = 1 To TableNo

            With .Tables(TableIndex)

                For TableRow = 1 To .Rows.Count

                 < SOME CODE HERE TO FIND NO. OF COLUMNS IN EACH ROW>

                Next                

            End With
            Next TableIndex
    End With
End Sub

我怎样才能遍历不平等的表,并得到它的每个单元格的内容?

ybzsozfc

ybzsozfc1#

以下是如何在行和单元格之间循环,即使单元格的数量可能因行而异:

Dim t As Table, r As Long, c As Long, rw As Row
Set t = ActiveDocument.Tables(1)

For r = 1 To t.Rows.Count
    Set rw = t.Rows(r)
    For c = 1 To rw.Cells.Count
        Debug.Print "In row " & r & " cell " & c
    Next c
Next r
rqdpfwrv

rqdpfwrv2#

尝试基于以下代码的操作:

Dim i As Long, wdRng As Object
With wdDoc.Tables(1).Range
  For i = 1 To .Cells.Count
    With .Cells(i)
      Set wdRng = .Range
      wdRng.End = wdRng.End - 1
      MsgBox "Row: " & .RowIndex & vbTab & "Col: " & .ColumnIndex & vbCr & "Text: " & vbTab & wdRng.Text
    End With
  Next
End With
5kgi1eie

5kgi1eie3#

我还没有找到一个不依赖于某种错误处理的选项。Resume Next应该对大多数任务都足够了。

Dim r As Integer
Dim c As Integer
Dim tbl As Table
Dim curCell As Cell

Set tbl = ActiveDocument.Tables(1)

On Error Resume Next

For r = 1 To tbl.Rows.count

    For c = 1 To tbl.Columns.count

        Set curCell = tbl.Cell(r, c)
        Debug.Print curCell.Range.text
    Next
Next

On Error GoTo 0

相关问题