vba 删除单词表中的特定行和列



我需要解析大部分word文档表并删除包含字符串"已删除"的单元格。表格具有不同的格式,因此我需要根据格式更改起始索引.我编写了一个代码,我首先开始删除包含"已删除"字符串的所有单元格的行。相同的策略用于删除列。它适用于行,但不适用于列删除。当运行表格单元格时,由于删除了列,列索引大于实际可用的列。我不知道为什么它发生在列删除部分而不是行删除部分。下面的代码适用于某些表,但不适用于所有表。

Dim msWord                          As Word.Application
Dim myDoc                           As Word.Document
Dim wordTable                       As Table
Dim r                               As Long
Dim c                               As Long
Dim col_del_cnt                     As Long
Dim row_del_cnt                     As Long
Dim i                               As Long
Dim col_index                       As Long
Dim param                           As Long
Dim Tbl                             As Table
Dim Tmpfile                         As String
Tmpfile = ThisWorkbook.Path & "Template.docx"
With msWord
.Visible = True
Set myDoc = .Documents.Open(Filename:=Tmpfile)
End With
With myDoc
For i = 7 To 21
Set wordTable = .Tables(i)
If wordTable.Columns.Count < 2 Then
col_index = 1
param = wordTable.Columns.Count
Else
col_index = 2
param = wordTable.Columns.Count - 1
End If
For r = 2 To wordTable.Rows.Count
col_del_cnt = 0
For c = col_index To wordTable.Columns.Count
If InStr(1, wordTable.Cell(r, c).Range.Text, "Deleted", 1) Then
col_del_cnt = col_del_cnt + 1
End If
Next c
If col_del_cnt = param Then
If r > wordTable.Rows.Count Then
wordTable.Rows(wordTable.Rows.Count).Delete
Else
wordTable.Rows(r).Delete
End If
End If
Next r
Next
End With
With myDoc
For i = 7 To 21
Set wordTable = .Tables(i)
If wordTable.Columns.Count < 2 Then
col_index = 1
Else
col_index = 2
End If
For c = col_index To wordTable.Columns.Count
row_del_cnt = 0
For r = 2 To wordTable.Rows.Count
If InStr(1, wordTable.Cell(r, c).Range.Text, "Deleted", 1) Then 'Error located here'
row_del_cnt = row_del_cnt + 1
End If
Next r
If row_del_cnt = wordTable.Rows.Count - 1 Then
If c > wordTable.Columns.Count Then
wordTable.Columns(wordTable.Columns.Count).Delete
Else
wordTable.Columns(c).Delete
End If
End If
Next c
Next
End With

我希望有人能帮助我找到解决方案。

删除索引的内容时,必须向后执行。

For i = 7 To 21
更改为

For i= 21 to 7 Step -1
等等。

当单元格中包含"已删除"时,您似乎正在尝试删除行和列。显然,如果您使用一个循环删除包含"已删除"的行,然后使用第二个循环删除包含"已删除"的列,则第二个循环将找不到任何内容。尝试基于以下内容:

Dim t As Long, r As Long, c As Long, ArrCols() As String
With myDoc
For t = 21 To 7 Step -1
With .Tables(t)
If InStr(1, .Range.Text, "Deleted", 1) Then
ReDim ArrCols(.Columns.Count)
For r = .Rows.Count To 1 Step -1
With .Rows(r)
If InStr(1, .Range.Text, "Deleted", 1) Then
For c = 1 To .Cells.Count
If InStr(1, .Cells(c).Range.Text, "Deleted", 1) Then
ArrCols(c) = c
End If
Next
.Delete
End If
End With
Next r
For c = UBound(ArrCols) To 1 Step -1
If ArrCols(c) <> "" Then .Columns(c).Delete
Next
End If
End With
Next
End With

请注意所有涉及删除的循环是如何向后运行的。

您自己的代码没有在行删除时引发错误这一事实只是一个巧合。

最新更新