《循环在WORD+VBA中的应用.doc
文本预览下载声明
循环在WORD VBA中的应用
[001]在活动文档的开头插入一张 4 列 3 行的表格。For Each...Next 结构用于循环遍历表格中的每个单元格。在 For Each...Next 结构中,InsertAfter 方法用于将文字添至表格单元格(单元格 1、单元格 2、以此类推)。
Sub CreateNewTable()
Dim docActive As Document
Dim tblNew As Table
Dim celTable As Cell
Dim intCount As Integer
Set docActive = ActiveDocument
Set tblNew = docActive.Tables.Add( _
Range:=docActive.Range(Start:=0, End:=0), NumRows:=3, _
NumColumns:=4)
intCount = 1
For Each celTable In tblNew.Range.Cells
celTable.Range.InsertAfter Cell intCount
intCount = intCount + 1
Next celTable
tblNew.AutoFormat Format:=wdTableFormatColorful2, _
ApplyBorders:=True, ApplyFont:=True, ApplyColor:=True
End Sub
[002]在活动文档中第一张表格的第一个单元格中插入文字。Cell 方法返回单独的 Cell 对象。Range 属性返回一个 Range 对象。Delete 方法用于删除现有的文字,而 InsertAfter 方法用于插入文字“Cell 1,1”。
Sub InsertTextInCell()
If ActiveDocument.Tables.Count = 1 Then
With ActiveDocument.Tables(1).Cell(Row:=1, Column:=1).Range
.Delete
.InsertAfter Text:=Cell 1,1
End With
End If
End Sub
[003]返回并显示文档中第一张表格的第一行中每个单元格的内容。
Sub ReturnTableText()
Dim tblOne As Table
Dim celTable As Cell
Dim rngTable As Range
Set tblOne = ActiveDocument.Tables(1)
For Each celTable In tblOne.Rows(1).Cells
Set rngTable = ActiveDocument.Range(Start:=celTable.Range.Start, _
End:=celTable.Range.End - 1)
MsgBox rngTable.Text
Next celTable
End Sub
Sub ReturnCellText()
Dim tblOne As Table
Dim celTable As Cell
Dim rngTable As Range
Set tblOne = ActiveDocument.Tables(1)
For Each celTable In tblOne.Rows(1).Cells
Set rngTable = celTable.Range
rngTable.MoveEnd Unit:=wdCharacter, Count:=-1
MsgBox rngTable.Text
Next celTable
End Sub
[004]在活动文档的开头插入用制表符分隔的文本,然后将这些文本转换为表格。
Sub ConvertExistingText()
With Documents.Add.Content
.InsertBefore one vbTab two vbTab three vbCr
.ConvertToTable Separator:=Chr(9), N
显示全部