我在 Word 中有一个包含数百个单元格的单列表(实际上是从 Excel 复制粘贴的)。我想使用 VBA 脚本循环遍历表格,按字母顺序排列每个单元格的内容。以下是表格中的示例摘录:
每个单元格的文本内容:
细胞1:
TM-102
Software V&V Summary
TM-044
Risk Management File RMF151
TM-081
TR-379
Cell2:[空 - 仅存在单元格结尾标记]
细胞3:
T-021
TR-1508
TR-1687
Environmental Footprint Analysis - TR-517
TM-044
Cytotoxicity Study Using the ISO Elution Method (1X MEM Extract) - TM-081
ISO Intracutaneous Study Extract - TM-102
Risk Management File RMF151 - All risks were mitigated to an acceptable level
细胞4:
Rest of World
Brazil
TÜV 19.1833
China
Certificate # 20162543150
Software V&V Summary
Risk Management File RMF151 - All risks were mitigated to an acceptable level.
TEST REPORT
Rest of World
Brazil
China
elements of the alarm systems for expected and unexpected alarm events.
Software V&V Summary
这是我写的代码(不优雅但不一定):
Sub Sort_cell()
'
' Sort_cell Macro
'
'
Dim count As Integer
Dim iteration As Integer
iteration = 0
count = ActiveDocument.Tables(1).Rows.count
If Selection.Information(wdWithInTable) Then
Selection.Tables(1).Range.Select
Selection.Collapse 1
End If
On Error Resume Next
While Selection.Information(wdWithInTable)
iteration = iteration + 1
Selection.Expand unit:=wdCell
Selection.MoveEnd unit:=wdCharacter, count:=-1
Selection.Sort ExcludeHeader:=False, FieldNumber:="Paragraphs", _
SortFieldType:=wdSortFieldAlphanumeric, SortOrder:=wdSortOrderAscending, _
FieldNumber2:="", SortFieldType2:=wdSortFieldAlphanumeric, SortOrder2:= _
wdSortOrderAscending, FieldNumber3:="", SortFieldType3:= _
wdSortFieldAlphanumeric, SortOrder3:=wdSortOrderAscending, Separator:= _
wdSortSeparateByTabs, SortColumn:=False, CaseSensitive:=False, LanguageID _
:=wdEnglishUS, SubFieldNumber:="Paragraphs", SubFieldNumber2:= _
"Paragraphs", SubFieldNumber3:="Paragraphs"
Selection.MoveRight unit:=wdCell, count:=1, Extend:=wdMove
If iteration = count Then
Exit Sub
End If
Wend
End Sub
发生的情况是,循环到达空的单元格 2,并且 Selection.MoveRight 命令选择整个表格,此时宏循环回到顶部并再次开始。我希望代码在遇到空单元格时直接跳到下一个单元格。
这似乎对我有用。
Sub Tester()
Dim tbl As Table, c As Cell, r As Row, rng As Range
If Not Selection.Information(wdWithInTable) Then Exit Sub
Set tbl = Selection.Tables(1)
For Each r In tbl.Rows 'loop over table rows
For Each c In r.Cells '...and the cells in each row
If Len(c.Range.Text) > 3 Then 'anything to sort?
Set rng = c.Range 'cell content
rng.MoveEnd wdCharacter, -2 'exclude "end of cell" marker
rng.Sort excludeheader:=False 'perform sort
End If
Next c
Next r
End Sub