2017-09-01 78 views
0

我正在編寫一個宏以將索引條目添加到表中的條目中。有些單元格包含一個需要添加條目的字符串,我已經設法完成該條目。例如,單元格包含'S875'。我用下面的代碼是:如何將數組中的字符串設置爲Word中的範圍VBA

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 

但我有一些細胞需要兩個或更多的索引條目添加,例如,S875,876我已經分裂這些到一個數組,可以循環通過數組,但我堅持如何設置範圍來添加索引條目。我所擁有的是:

If Len(oem) > 6 Then 
    oemArray() = Split(oem, ", ") 
    For i = LBound(oemArray) To UBound(oemArray) 
       'need to use Indexes.MarkEntry to add an index entry for each 
       ' string in the array 
       Debug.Print oemArray(i) 
    Next i 
End If 

所以,我認爲我要麼需要在選擇某種方式改變爲每個條目陣列上或使用範圍,但我不知道到底是什麼?

回答

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對象靜靜地在屏幕後面工作。

相關問題