我一直在尝试使用VBA查找Word表格中的第一个空单元格。
下面的代码查找所有空单元格,而不是查找填充单元格之后的第一个单元格。如何解决这个问题?
For Each oRow In Selection.Tables(1).Rows
For Each oCell In oRow.Cells
If Selection.Text = Chr(13) & Chr(7) Then
oCell.Select
'Selection.PasteSpecial DataType:=wdPasteText
MsgBox oCell.RowIndex & " " & oCell.ColumnIndex & " is empty."
End If
Next oCell
Next oRow
发布于 2020-03-18 17:27:36
这就是你所想的吗?
Sub FindNextBlank()
Dim Tbl As Table
Dim TblRow As Row
Dim HasText As Boolean
Dim LookForText As Boolean, Done As Boolean
Dim R As Long, C As Long
Dim Txt As String
LookForText = True
With ThisDocument.Tables(1)
For R = 1 To .Rows.Count
Set TblRow = .Rows(R)
For C = 1 To TblRow.Cells.Count
HasText = (Len(TblRow.Cells(C).Range.Text) > 2)
If HasText = LookForText Then
If LookForText Then
LookForText = Not LookForText
Else
Done = True
TblRow.Cells(C).Range.Select
Exit For
End If
End If
Next C
If Done Then Exit For
Next R
If Done Then
Txt = "Cell #" & C & " in row " & R & " is free."
Else
Txt = "No free cell was found that" & vbCr & _
" follows one that has text."""
End If
End With
MsgBox Txt, vbInformation, "Search result"
End Sub
For ... Each
更快,但我本能地不相信它,因为它们中项的顺序通常由它们的创建顺序决定。这可能是也可能不是从上到下,从左到右。通过坐标调用单元格可能需要更长的时间,但您可以保持对顺序的控制。
发布于 2020-03-18 18:01:03
正如您可能已经发现的,确定Word中的空单元格并不像看起来那么简单。下面的代码查找删除所有空格、制表符和vbCr后,单元格中文本长度为1的第一个单元格。您可以将其扩展为还查找vbLF、手动换行符和其他字符,这些字符可能在单元格中,但如果您关闭了视图文本标记,则这些字符将不可见。
表区域的.Cells方法是最适合在这里使用的工具,因为即使表具有合并的单元格,它也可以正常工作。如果表格中存在合并的单元格,则使用单元格坐标搜索表格将失败。使用.Cells方法,从左上角到右下角(逐行逐列)搜索表。
Option Explicit
Sub Test()
Dim myCell As Word.Range
Set myCell = FirstEmptyCell(ActiveDocument.Tables(1).Range)
myCell.Select
End Sub
' Returns the first cell that has a text length of 1
' after removing spaces and tab characters from the cell text
Public Function FirstEmptyCell(ByVal TableRange As Word.Range) As Word.Range
Dim myCell As Word.Cell
For Each myCell In TableRange.Tables(1).Range.Cells
Dim CellText As String
CellText = myCell.Range.Text
CellText = Replace(CellText, vbTab, vbNullString)
CellText = Replace(CellText, " ", vbNullString)
CellText = Replace(CellText, vbCr, vbNullString)
If Len(CellText) = 1 Then
Set FirstEmptyCell = myCell.Range
Exit Function
End If
Next
End Function
发布于 2020-03-18 20:04:49
这个解决方案真的比其他“答案”建议的简单得多:
Dim i As Long
With Selection
If .Information(wdWithInTable) = True Then
With .Tables(1).Range
For i = 1 To .Cells.Count
With .Cells(i)
If Len(.Range.Text) = 2 Then
MsgBox " Row " & .RowIndex & ", Column " & .ColumnIndex & " is empty."
.Range.PasteSpecial DataType:=wdPasteText
Exit For
End If
End With
Next
End With
Else
MsgBox "No table selected", vbExclamation
End If
End With
我甚至添加了一些错误检查。
https://stackoverflow.com/questions/60736008
复制相似问题