呈现的代码不适用于由单行组成的表。这个Do While
循环:
Do While tRng.Cells(1).RowIndex = 1
tRng.Move unit:=wdCell, Count:=1
Loop
一旦我们找到一个不在第 1 行的单元格,就会爆发。如果只有一行,那么每个单元格都在第 1 行。
Move
如果移动不成功,该方法返回 0,所以这应该有效:
Dim lngSuccess As Long
For Each ttable In ThisDocument.Tables
Set tRng = ttable.Cell(1, 1).Range
sngWdth = -tRng.Information(wdHorizontalPositionRelativeToPage)
' Any non-zero value will do here
lngSuccess = 1
Do While tRng.Cells(1).RowIndex = 1 And lngSuccess <> 0
lngSuccess = tRng.Move(unit:=wdCell, Count:=1)
Loop
tRng.MoveEnd wdCharacter, -1
sngWdth = sngWdth + tRng.Information(wdHorizontalPositionRelativeToPage)
MsgBox PointsToInches(sngWdth)
Next tTable
另请注意:tTable
未在您的原始代码中声明,因此请在方法中声明它(Option Explicit
如果尚未这样做,请使用)。当 Word 停止响应时,可以通过按下来跟踪导致错误的代码部分<Ctrl>-<Break>
- 这将直接引导您进入While
循环
编辑以处理单行表上的不正确宽度:
这个新版本使用该Cell.Width
属性来测量表格的宽度。我找不到一种可靠的方法Range.Information
来测量单行表的宽度
Option Explicit
Sub fixTableAlignment()
Dim tTable As Table
Dim cCell As Cell
Dim sngWdth As Single
Dim bFinished As Boolean
For Each tTable In ThisDocument.Tables
Set cCell = tTable.Cell(1, 1)
sngWdth = 0
' Can't just check the row index as cCell
' will be Nothing when we run out of cells
' in a single-row table. Can't check for
' Nothing and also check the row index in
' the Do statement as VBA doesn't short-circuit
bFinished = False
Do Until bFinished
sngWdth = sngWdth + cCell.Width
Set cCell = cCell.Next
If (cCell Is Nothing) Then
bFinished = True
ElseIf (cCell.RowIndex <> 1) Then
bFinished = True
End If
Loop
MsgBox PointsToInches(sngWdth)
Next tTable
End Sub