如何将数组中的字符串设置为Word VBA中的Range

时间:2017-09-01 05:11:01

标签: vba word-vba

我正在编写一个宏来将索引条目添加到word中的表中的条目中。有些单元格包含一个字符串,需要添加我已设法完成的条目。例如,单元格包含' S875'我已经使用了以下代码:

dealloc

但是我有一些需要添加两个或更多索引条目的单元格,例如S875,876。我已经将这些条目拆分成一个数组并且可以循环遍历数组但是我仍然坚持如何设置要添加索引条目的范围。我所拥有的是:

For Each oRow In oTable.Rows
If oRow.Cells.count = 4 Then
    oTable.Cell(oRow.Index, 4).Select
    Selection.Expand unit:=wdCell
    oem = Left$(Selection.Text, Len(Selection.Text) - 2)

    If (oem Like "*O.E.M*") Or (oem Like "*OEM*") Then
          'ignore this row
          Debug.Print oem
   Else
     ActiveDocument.Indexes.MarkEntry Range:=Selection.Range, Entry:=oem, _
     EntryAutoText:=oem, CrossReference:="", CrossReferenceAutoText:="", 
     BookmarkName:="", Bold:=False, Italic:=False
    End If
   End If
  Next oRow

所以我想我要么以某种方式将选择更改为阵列上的每个条目或使用范围,但我不确定?

1 个答案:

答案 0 :(得分:1)

你正是在正确的道路上。有了一点耐心,你肯定会完成它。

Sub WriteIndex()

    Dim Rng As Range
    Dim oTable As Table
    Dim oRow As Row
    Dim Oem As String
    Dim Sp() As String, i As Integer

    Set oTable = ActiveDocument.Tables(2)           ' used for my test
    For Each oRow In oTable.Rows
        ' in essence, if you have any merged cells in any row in
        ' the table your row counter will be thrown off
        If oRow.Cells.Count = 4 Then
            Set Rng = oRow.Cells(4).Range           ' avoiding the Selection object
            Rng.MoveEnd wdCharacter, -1
            Oem = Rng.Text
            ' your "Like" code seems to be case sensitive
            ' if so, this should be more flexible
            If (InStr(1, Oem, "O.E.M", vbTextCompare)) Or _
               (InStr(1, Oem, "OEM", vbTextCompare)) Then
                  'ignore this row
                  Debug.Print "Found: "; Oem
            Else
                Sp = Split(Oem, ",")
                For i = 0 To UBound(Sp)
                    With ActiveDocument
                        ' it seems that all but the first two properties
                        ' are optional and can be omitted if not set
                        .Indexes.MarkEntry Range:=Rng, _
                                           Entry:=Trim(Sp(i)), _
                                           EntryAutoText:=Trim(Sp(i)), _
                                           CrossReference:="", _
                                           CrossReferenceAutoText:="", _
                                           BookmarkName:="", _
                                           Bold:=False, _
                                           Italic:=False, _
                                           Reading:=""
                    End With
                Next i
            End If
        End If
    Next oRow
End Sub

请注意Split("S675", ",")返回一个包含单个元素的数组。因此,您可以使用相同的代码处理单个索引和多个索引。

使用Selection对象比Range对象慢,因为必须为每个选择更新屏幕。 Range对象在屏幕后面安静地工作。