08.02.2019, 17:00
Hallo,
ich habe einen Excel-Code zum Erstellen von Serienbriefen über einen Command Button, der schon gut funktioniert, aber ich habe damit noch ein Problem:
Momentan wird der Code nur auf ein Word-Dokument angewandt, das sb1.docx heißt. Und nur dann wenn in Spalte A (sie heißt "Anz") die Zahl > 0 ist.
Nun soll aber je nachdem welche Zahl (1-5) in Spalte A (Anz) steht das entsprechende Word Doc (sb1 - sb5) genommen werden.
Geht das irgendwie?
ich habe einen Excel-Code zum Erstellen von Serienbriefen über einen Command Button, der schon gut funktioniert, aber ich habe damit noch ein Problem:
Momentan wird der Code nur auf ein Word-Dokument angewandt, das sb1.docx heißt. Und nur dann wenn in Spalte A (sie heißt "Anz") die Zahl > 0 ist.
Nun soll aber je nachdem welche Zahl (1-5) in Spalte A (Anz) steht das entsprechende Word Doc (sb1 - sb5) genommen werden.
Geht das irgendwie?
Code:
Private Sub CommandButton1_Click()
Application.ScreenUpdating = False
Dim StrMMSrc As String, StrMMDoc As String, StrMMPath As String, StrName As String
Dim i As Long, j As Long
Const StrNoChr As String = """*./\:?|"
Dim wdApp As New Word.Application, wdDoc As Word.Document
wdApp.Visible = False
wdApp.DisplayAlerts = wdAlertsNone
StrMMSrc = ThisWorkbook.FullName
StrMMPath = ThisWorkbook.Path & "\"
StrMMDoc = StrMMPath & "sb1.docx"
Set wdDoc = wdApp.Documents.Open(Filename:=StrMMDoc, AddToRecentFiles:=False, ReadOnly:=True, _
Visible:=False)
With wdDoc
With .MailMerge
.MainDocumentType = wdFormLetters
.OpenDataSource Name:=StrMMSrc, ReadOnly:=True, AddToRecentFiles:=False, _
LinkToSource:=False, Connection:="Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;" & _
"Data Source=StrMMSrc;Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
SQLStatement:="SELECT * FROM `Sheet1$` where (Anz>0)"
For i = 1 To .DataSource.RecordCount
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = i
.LastRecord = i
.ActiveRecord = i
If Trim(.DataFields("ID")) = "" Then Exit For
StrName = .DataFields("ID")
End With
.Execute Pause:=False
For j = 1 To Len(StrNoChr)
StrName = Replace(StrName, Mid(StrNoChr, j, 1), "_")
Next
StrName = Trim(StrName)
With wdApp.ActiveDocument
.SaveAs Filename:=StrMMPath & StrName & ".docx", FileFormat:=wdFormatXMLDocument, _
AddToRecentFiles:=False
.Close SaveChanges:=False
End With
Next i
.MainDocumentType = wdNotAMergeDocument
End With
.Close SaveChanges:=False
End With
wdApp.DisplayAlerts = wdAlertsAll
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing
Application.ScreenUpdating = False
End Sub