如何确定选择何时在表格单元格的末尾?

时间:2014-07-19 01:43:00

标签: vba ms-word word-vba

如何确定选择何时在表格单元格的末尾?

1 个答案:

答案 0 :(得分:2)

下面给出了提供相对于表的选择信息的例程,并确定选择是否在表格单元格的末尾。

Option Explicit

Sub Main()
  Selection.Collapse ' defaults to wdCollapseStart
  Dim v1 As Variant
  v1 = TblInfo
  MsgBox "Tbl: " & v1(0) & ", Row: " & v1(1) & ", Col: " & v1(2)
  MsgBox "isEndOfCell is " & isEndOfCell()
End Sub

Function TblInfo() As Variant ' returns tbl#, row#, col#
  ' returns #tbls, 0, 0 if not in table (#tbls before selection)
  Selection.Collapse ' ??
  If Selection.Information(wdWithInTable) Then
    TblInfo = Array( _
      Range(0, Selection.Tables(1).Range.End).Tables.Count, _
      Selection.Information(wdStartOfRangeRowNumber), _
      Selection.Information(wdStartOfRangeColumnNumber))
  Else
    TblInfo = Array( _
      Range(0, Selection.End).Tables.Count, 0, 0)
  End If
End Function

Function isEndOfCell() As Boolean ' True if at end
  Dim v1 As Variant, v2 As Variant
  Selection.Collapse ' ??
  If Not Selection.Information(wdWithInTable) Then MsgBox "Oops, not in table.": End
  v1 = TblInfo()
  Selection.MoveRight wdCharacter, 1
  v2 = TblInfo()
  Selection.MoveLeft wdCharacter, 1
  If Not ArraysEq(v1, v2) Then isEndOfCell = True
End Function

Function ArraysEq(v1 As Variant, v2 As Variant) As Boolean
  ' compares variant arrays, true if eq
  Dim i1&
  If UBound(v1) <> UBound(v2) Then Exit Function
  For i1 = 0 To UBound(v1)
    If v1(i1) <> v2(i1) Then Exit Function
  Next i1
  ArraysEq = True
End Function