View Single Post
  #2   Report Post  
Posted to microsoft.public.excel.programming
Per Jessen Per Jessen is offline
external usenet poster
 
Posts: 1,533
Default Macro with FOR - IF Loop


"Ruth" skrev i en meddelelse
...

Hi,

The idea with the macro below is to take several cells from a row in EXCEL
and use then to fill in a form previously defined in a WORD file. The
approach below in principle is working fine but I guess there should a
more
efficient way to do the loop(I use a main "For" loop with several "IF"
nested, one for each potential field to be filled in the form). As I
said, I
checked it out and it works but the form has around 30 fields and I would
like to know whether there is a more elegant way to program it.

Thanks!!


Dim wordApp, wdFF As Object, wordFile As Object, myFile As String, I,
fila As Integer
myFile = "NEW_FORM.doc"
Set wordApp = CreateObject("Word.Application")
Set wordFile = wordApp.Documents.Open(myFile)
.......
fila = 3
I = 1
For Each wdFF In wordFile.Formfields
If wdFF.Name = "Text1" Then
wdFF.Result = Range("H" & fila)
End If
If wdFF.Name = "Dropdown2" Then
wdFF.DropDown.Value = Left(Range("A" & fila), 1) + 1
End If

If wdFF.Name = "Text3" Then
wdFF.Result = Range("T" & fila)
End If
...................
I = I + 1
Next
wordApp.Quit
Set wordFile = Nothing
Set wordApp = Nothing
End Sub


Hi Ruth

With "Select Case" your code will be like this:

Sub BuildForm()
fila = 3
I = 1
For Each wdFF In wordFile.Formfields
Select Case wdFF
Case wd.Name = "Text1"
wdFF.Result = Range("H" & fila)
Case wd.Name = "Dropdown2"
wdFF.DropDown.Value = Left(Range("A" & fila), 1) + 1
Case wdFF.Name = "Text3"
wdFF.Result = Range("T" & fila)
End Select
Next
End Sub

Regards,

Per