VBA实现Word表格转Excel:跳过含合并单元格的行
解决Word表格合并行跳过问题的VBA代码修改
针对你的需求,我们可以通过计算每行的逻辑列数总和来判断是否存在合并单元格,从而跳过不符合要求的行。以下是修改后的完整代码:
Sub extractData() Dim wd As New Word.Application Dim doc As Word.Document Dim sh As Worksheet Dim Tbls As Word.Tables, r As Word.Row, cell As Word.Cell Dim totalCols As Integer Dim currentColSum As Integer wd.Visible = True Set doc = wd.Documents.Open("\\file.docx", ReadOnly:=True) Set Tbls = doc.Tables totalCols = Tbls(1).Columns.Count ' 获取目标表格的总列数(这里应为6) Set sh = ActiveSheet For Each r In Tbls(1).Rows ' 计算当前行的逻辑列数总和(合并单元格会跨多列,累加每格的列跨度) currentColSum = 0 For Each cell In r.Cells currentColSum = currentColSum + cell.Columns.Count Next cell ' 若逻辑列数不等于总列数,说明存在合并单元格,跳过该行 If currentColSum <> totalCols Then Continue For End If ' 复制无合并的行数据到Excel For Each cell In r.Cells sh.Cells(r.Index, cell.Column.Index).Value = Application.WorksheetFunction.Clean(cell.Range.Text) Next cell Next r ' 清理Word进程,避免后台残留 doc.Close SaveChanges:=False wd.Quit Set doc = Nothing Set wd = Nothing End Sub
关键修改说明:
- 逻辑列数计算:通过累加每行每个单元格的
Columns.Count属性(该值表示单元格跨的列数),得到该行的实际逻辑列数总和。如果总和不等于表格总列数(6),则说明该行存在合并单元格。 - 跳过不合规行:使用
Continue For直接跳过当前行的后续处理,进入下一行循环。如果你的VBA版本不支持Continue For,可以替换为GoTo跳转写法:If currentColSum <> totalCols Then GoTo NextRow End If ' ...数据复制代码... NextRow: Next r - 进程清理:新增了关闭Word文档和退出应用的代码,避免运行后后台残留Word进程。
内容的提问来源于stack exchange,提问作者JD88
相关产品推荐
相关产品推荐

