Страницы: 1
RSS
VBA. Слияние Excel и Word по шаблону
 
Уважаемые Знатоки! Помогите, пожалуйста подправить код:
1. Если в Word типлейте 2 раза указано поле для замены (например, &ContractNumber), оно не заполняется. Как заставить VBA заменить все встреченные, а не только 1е встреченное словосочетание.
2. Если файл с таким именем существует, VBA выдает ошибку. Можно ли файл просто заменить на новый с таким же именем?
Код
Sub FillInNotifNew()

Sheets("For Notif (new)").Select

Dim wdApp As Object
Dim wdDoc As Object

HomeDir$ = ThisWorkbook.Path

Set wdApp = CreateObject("Word.Application")
I% = 2

Do
If Cells(I%, 1).Value = "" Then Exit Do
If Cells(I%, 1).Value <> "no" Then

NPP$ = Cells(I%, 1).Text

' äëÿ çàïîëíåíèÿ óâåäîìëåíèÿ
CustomerNameFull$ = Cells(I%, 5).Text
ContractNumber$ = Cells(I%, 6).Text
ContractDate$ = Cells(I%, 7).Text
TermAgreemDate$ = Cells(I%, 8).Text
NotifDate$ = Cells(I%, 9).Text
Distributor$ = Cells(I%, 10).Text
Bonus$ = Cells(I%, 11).Text
Points$ = Cells(I%, 12).Text
AmountWritten$ = Cells(I%, 13).Text
POA$ = Cells(I%, 14).Text
BonPeriod$ = Cells(I%, 17).Text

' äëÿ íàçâàíèÿ ôàéëà
PeriodForFile$ = Cells(I%, 15).Text
ContractForFile$ = Cells(I%, 16).Text
CustomerForFile$ = Cells(I%, 4).Text

FileCopy HomeDir$ + "\template_new.docx", HomeDir$ + "\" + "Bonus Lease (" + ContractForFile$ + ") - " + CustomerForFile$ + "_ " + PeriodForFile$ + ".docx"
Set wdDoc = wdApp.Documents.Open(HomeDir$ + "\" + "Bonus Lease (" + ContractForFile$ + ") - " + CustomerForFile$ + "_ " + PeriodForFile$ + ".docx")

wdDoc.Range.Find.Execute FindText:="&CustomerNameFull", ReplaceWith:=CustomerNameFull$
wdDoc.Range.Find.Execute FindText:="&ContractNumber", ReplaceWith:=ContractNumber$
wdDoc.Range.Find.Execute FindText:="&ContractDate", ReplaceWith:=ContractDate$
wdDoc.Range.Find.Execute FindText:="&TermAgreemDate", ReplaceWith:=TermAgreemDate$
wdDoc.Range.Find.Execute FindText:="&NotifDate", ReplaceWith:=NotifDate$
wdDoc.Range.Find.Execute FindText:="&Distributor", ReplaceWith:=Distributor$
wdDoc.Range.Find.Execute FindText:="&Bonus", ReplaceWith:=Bonus$
wdDoc.Range.Find.Execute FindText:="&Points", ReplaceWith:=Points$
wdDoc.Range.Find.Execute FindText:="&AmountWritten", ReplaceWith:=AmountWritten$
wdDoc.Range.Find.Execute FindText:="&POA", ReplaceWith:=POA$
wdDoc.Range.Find.Execute FindText:="&BonPeriod", ReplaceWith:=BonPeriod$

wdDoc.Save
wdDoc.Close

End If

I% = I + 1
Loop

wdApp.Quit

MsgBox "Ãîòîâî!"

End Sub
 
Код
Replace:=wdReplaceAll
Изменено: БМВ - 23.06.2020 13:11:00
По вопросам из тем форума, личку не читаю.
 
куда это вписывать, не совсем понятно
Страницы: 1
Наверх