简体   繁体   中英

Word vba multiple table selection

I need a VBA code for MS Word that selects multiple tables (of my choosing) and inputs a string based on the textbox object. I've written a code that does this, but it would become repetitive if I was to select large number of tables.

Private Sub Claim_Change()

  Dim j As Table
  Set j = ActiveDocument.Tables(2)
  Dim k As Table
  Set k = ActiveDocument.Tables(3)

'Input claim
j.Select
Selection.Delete

With j
.Cell(1, 1).Range.InsertAfter "Claim #: " & Claim
.Cell(1, 2).Range.Text = Format(Date, "MMMM DD, YYYY ")
.Columns.AutoFit
End With

k.Select
Selection.Delete

With k
.Cell(1, 1).Range.InsertAfter "Claim #: " & Claim
.Cell(1, 2).Range.Text = Format(Date, "MMMM DD, YYYY ")
.Columns.AutoFit

End With
Claim.Select

End Sub

Is there a simpler way to put this code together?

You can use the following pattern (I removed some data, but it will give you the idea) to handle it more easily:

Option Explicit

Private Sub Claim_Change()

Dim myTable As Table
Dim tables() As Variant
Dim tableCounter As Long

tables = Array(1, 2, 5, 21)

For tableCounter = LBound(tables) To UBound(tables)

   ActiveDocument.tables(tables(tableCounter)).Select
   Selection.Delete

Next tableCounter

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM