Hekko Hekko - 5 months ago 11
Vb.net Question

How to shorten this code?

Can I somehow shorten this code I wrote? Can I find what exists and then do the action or must i write this many IFs every time?

If someone is wondering what it does: code finds out if a Form Field with a specific name in Word exists and then selects it.

If ActiveDocument.Bookmarks.Exists("TEXT1") = True Then
With ActiveDocument.FormFields("TEXT1")
.Select
End With
End If
If ActiveDocument.Bookmarks.Exists("TEXT2") = True Then
With ActiveDocument.FormFields("TEXT2")
.Select
End With
End If
If ActiveDocument.Bookmarks.Exists("TEXT3") = True Then
With ActiveDocument.FormFields("TEXT3")
.Select
End With
End If
If ActiveDocument.Bookmarks.Exists("TEXT3") = True Then
With ActiveDocument.FormFields("TEXT3")
.Select End With End If
If ActiveDocument.Bookmarks.Exists("TEXT4") = True Then
With ActiveDocument.FormFields("TEXT4")
.Select
End With
End If
If ActiveDocument.Bookmarks.Exists("TEXT5") = True Then
With ActiveDocument.FormFields("TEXT5")
.Select
End With
End If
If ActiveDocument.Bookmarks.Exists("TEXT6") = True Then
With ActiveDocument.FormFields("TEXT6")
.Select
End With
End If

Answer

You need a for-loop to iterate over the fields. Pseudo-code goes something like this ...

for (i = 1 ... 6)
  name = "Text" + i
  If ActiveDocument.Bookmarks.Exists(name) = True Then
    With ActiveDocument.FormFields(name)
      .Select
    End With
  End If
end for

for in vb.net => For i As Integer = 0 To 5

variables in vb.net =>

Dim name As String

name = "Text" & i // I think