如果单元格为空,Word 宏从表格中删除行 [英] Word Macro Remove Rows from Table If Cell Empty
问题描述
我正在尝试运行一个宏,该宏将检查所选表格中第 2 列中的空单元格,如果有空单元格,则删除该行.
I am trying to run a Macro that will check a selected table for empty cells in column 2, and if there are empty cells, delete that row.
Sub DeleteEmptyRows()
Set Tbl = Selected.Tables(1)
With Tbl
noOfCol = Tbl.Range.Rows(1).Cells.Count
With .Range
For i = .Cells.Count To 1 Step -1
On Error Resume Next
If Len(.Cells(i).Range) = 2 Then
.Rows(.Cells(i).RowIndex).Delete
j = i Mod noOfCol
If j = 0 Then j = noOfCol
End If
Next i
End With
End With
End Sub
它非常接近我想要的,但我不确定如何在第 2 列中指定空单元格.我还尝试将 noOfCol 行更改为:
And it's really close to what I want, but I'm just not sure how to specify empty cells in column 2. I also tried changing the noOfCol line to:
Selection.SetRange Selection.Tables(1).Rows(2).Cells(2).Range.Start, _
Selection.Tables(1).Rows.Last.Cells(2).Range.End
但这仍然会删除任何列为空的行.我需要它只删除第 2 列为空的行.谢谢
But that still deletes rows where any column is empty. I need it to delete only rows where column 2 is empty. Thanks
推荐答案
处理列中的所有单元格是一个问题,因为无法为列设置 Range
.Range
必须是文档中的一组连续字符.虽然一列看起来是连续的,但在幕后,它的内容实际上不是.表格的字符从左上到右,从上到下(行).
Working with all the cells in column is a problem because it's not possible to set a Range
to a column. A Range
must be a continguous set of characters in the document. While a column looks contiguous, behind the scenes its content is actually not. The characters of a table run from top-left to the right, and top-to-bottom (the rows).
最接近的代码是选择列然后在 Selection
对象中工作.或循环行.
The closest code can get is to select the column then work in the Selection
object. Or loop the rows.
以下代码示例演示了如何循环行" - 类似于问题中的代码使用的内容.这里的关键是使用 Table.Cells
进行循环,For
计数器指定行索引,列号 (2) 指定列索引.>
The following code sample demonstrates how to "loop the rows" - similar to what the code in the question uses. The key here is to use the Table.Cells
for the loop, with the For
counter designating the row index and the column number (2) designating the column index.
Sub ProcessColTwo()
Dim tbl As Word.Table
Dim nrRows As Long, ColToCheck As Long, i As Long
Dim cellRange As Word.Range
Set tbl = ActiveDocument.Tables(1)
nrRows = tbl.Rows.Count
ColToCheck = 2
For i = nrRows To 1 Step -1
Set cellRange = tbl.Cell(i, ColToCheck).Range
If Len(cellRange.text) = 2 Then
cellRange.Rows(1).Delete
End If
Next i
End Sub
这里的代码演示了如何使用 Selection
And here's code that demonstrates using Selection
Sub ProcessColTwo()
Dim tbl As Word.Table
Dim ColToCheck As Long
Dim cel As Word.Cell
Set tbl = ActiveDocument.Tables(1)
ColToCheck = 2
tbl.Columns(ColToCheck).Select
For Each cel In Selection.Cells
If Len(cel.Range.text) = 2 Then
cel.Range.Rows(1).Delete
End If
Next
End Sub
这篇关于如果单元格为空,Word 宏从表格中删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!