Hallo,
heutezutage würde ich eher ein Ritch-Text-Steuerelement in einem Word-Dokument einfügen. Diese sind wesentlich flexibler, als die alten Formular-Steuerelremente.
Falls im Word-Dokument ein Steuerelement mit dem Tag "Text1" vorhanden ist, wird dieses mit einem Text gefüllt.
Zusätzlich kann auch in Word eingestellt werden ob das Steuerelement selbst nach dem Ausfüllen noch als solcxhes ebestehen bleiben soll.
Private Sub cmdtest_Click()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim ctrlText1 As Word.ContentControl
Dim Pfad As String
Pfad = ThisWorkbook.Path & "\Vorlage2.docx"
On Error GoTo Err_Handler
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(Pfad)
wrdApp.Visible = False
Set ctrlText1 = SearchContentControl(wrdDoc, "Text1")
If Not ctrlText1 Is Nothing Then
ctrlText1.Range.Text = "Test erfolgreich"
End If
' wrdDoc.FormFields("Text1").Value = "test erfolgreich"
Pfad = ThisWorkbook.Path & "\Testpfad\" & "Fertig" & ".pdf"
wrdDoc.Save
wrdDoc.Close
Err_Exit:
If Not wrdAp Is Nothing Then
wrdApp.Quit True
End If
Set wrdDoc = Nothing
Set wrdApp = Nothing
Exit Sub
Err_Handler:
MsgBox "Es ist ein Fehler aufgetreten.", vbInformation
Err.Clear
Resume Err_Exit
End Sub
Function SearchContentControl(Doc As Word.Document, Tag As String) As Word.ContentControl
Dim ctrl As Word.ContentControl
For Each ctrl In Doc.ContentControls
If ctrl.Tag = Tag Then
Set SearchContentControl = ctrl
Exit For
End If
Next
End Function
Da dieser VBA-Code von Excel aus ausgeführt werden soll, muss ein Verweis auf "Microsoft Word" vorhanden sein.
Ein funktionierendes Beispiel ist hier abgelegt: https://www.dropbox.com/s/rux8rtycm7shdnc/Als%20Word-Dokument%20speichern.zip?dl=0
LG, BigBen
|