我研究了VBA中的表格单元对象和选择对象文档,但没有发现在保留单元格本身的情况下删除Word中的单元格内容的方法。与Excel相比,这似乎很容易实现,而在Word中却几乎不可能。
我需要删除一些包含文本的单元格,还有一些包含文本表单域。你有什么想法吗?
我需要删除一些包含文本的单元格,还有一些包含文本表单域。你有什么想法吗?
这个有效:
ActiveDocument.Tables(1).Cell(1, 2).Select
Selection.Delete
这会删除单元格的内容,但保留空单元格。
我理解您的沮丧,因为奇怪的是,上面的代码并不与下面的代码执行相同的操作:
ActiveDocument.Tables(1).Cell(1, 2).Delete
这两种做法有所不同,一种是选中单元格后按下键盘上的Delete键(此操作会清空单元格内容但保留单元格只是变为空白),另一种是右键点击选中单元格并选择“删除单元格…”(此操作会将整个单元格删除)。
Select
方法,则以下内容正是您要找的:ActiveDocument.Tables(1).Cell(1, 1).Range.Text = ""
它也会删除图像和内容控件。
我从互联网的各个部分拼凑了这个...包括来自VBA Express的Fumei。它运行良好。选择表格中的任何单元格并运行宏deleteTableCells即可。
Sub deleteTableCells()
Dim selectedRange As Range
On Error GoTo Errorhandler
Set selectedRange = SelectionInfo
selectedRange.Delete
Errorhandler:
Exit Sub
End Sub
Function SelectionInfo() As Range
'
Dim iSelectionRowEnd As Integer
Dim iSelectionRowStart As Integer
Dim iSelectionColumnEnd As Integer
Dim iSelectionColumnStart As Integer
Dim lngStart As Long
Dim lngEnd As Long
' Check if Selection IS in a table
' if not, exit Sub after message
If Selection.Information(wdWithInTable) = False Then
Err.Raise (2022)
Else
lngStart = Selection.Range.Start
lngEnd = Selection.Range.End
' get the numbers for the END of the selection range
iSelectionRowEnd = Selection.Information(wdEndOfRangeRowNumber)
iSelectionColumnEnd = Selection.Information(wdEndOfRangeColumnNumber)
' collapse the selection range
Selection.Collapse Direction:=wdCollapseStart
' get the numbers for the END of the selection range
' now of course the START of the previous selection
iSelectionRowStart = Selection.Information(wdEndOfRangeRowNumber)
iSelectionColumnStart = Selection.Information(wdEndOfRangeColumnNumber)
' RESELECT the same range
Selection.MoveEnd Unit:=wdCharacter, Count:=lngEnd - lngStart
' set the range of cells for consumption
With ActiveDocument
Set SelectionInfo = .Range(Start:=.Tables(1).cell(iSelectionRowStart, iSelectionColumnStart).Range.Start, _
End:=.Tables(1).cell(iSelectionRowEnd, iSelectionColumnEnd).Range.End)
End With
End If
End Function
Private Sub cbClearTable_Click()
'mouse cursor must be in the table for clearing
Dim cell_BhBp As Cell
For Each cell_BhBp In Selection.Tables(1).Range.Cells
cell_BhBp.Range = ""
Next
End Sub
以上代码清除当前表格/鼠标光标所在的表格中所有单元格的内容。
另一种清除文档中第一个表格所有单元格的方法是
ActiveDocument.Tables(1).Range.Delete
或者针对当前表格/光标所在位置
Selection.Tables(1).Range.Delete
Private Sub CommandButton40_Click()
Application.Activate
SendKeys ("{DEL}")
End Sub
以上代码会清除所有选定单元格的内容。在这种情况下,所选单元格可能不相邻。当用户表单中的按钮被点击时,此代码会被触发。