hearthhrob4gals
Board Regular
- Joined
- Aug 20, 2014
- Messages
- 142
hi,
my below code works well when no word document is opened prior to running the macro. However, if there is already an opened word document, and then another word document is opened through the macro thn instead of executing data from the newly opened doc, it takes data from the previously opened doc.
problem is that it should consider DOCFilenm as active doc ,however if any xyz word doc was open before running the macro it consider that file as active instead of DOCFilenm
my below code works well when no word document is opened prior to running the macro. However, if there is already an opened word document, and then another word document is opened through the macro thn instead of executing data from the newly opened doc, it takes data from the previously opened doc.
Code:
Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open DOCFilenm
wordapp.Visible = True
wordapp.Activate
Documents.Open(DOCFilenm).Activate
Set wdDoc = wordapp.ActiveDocument
ActiveDocument.MailMerge.MainDocumentType = wdFormLetters
ActiveDocument.MailMerge.OpenDataSource Name:=ExcelFilenm, Format:=wdOpenFormatAuto, Connection:="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=ExcelFilenm" _
, SQLStatement:="SELECT * FROM `'60 Days$'`", SQLStatement1:="", SubType:=wdMergeSubTypeAccess
For x = 1 To LS60
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = ActiveDocument.MailMerge.DataSource.ActiveRecord
.LastRecord = ActiveDocument.MailMerge.DataSource.ActiveRecord
End With
.Execute Pause:=False
End With
ChangeFileOpenDirectory DirPath
On Error Resume Next
dt = ExcelWbk.Sheets("60 Days").Range("F" & x + 1).Value
dt = Replace(dt, "/", "-")
dt = Replace(dt, "\", "-")
dt = Format(dt, "mm-dd-yyyy")
On Error GoTo 0
EmpId = ExcelWbk.Sheets("60 Days").Range("C" & x + 1).Value
CostCenter = ExcelWbk.Sheets("60 Days").Range("B" & x + 1).Value
CostCenter = Trim(Left(CostCenter, 4))
CardMemName = ExcelWbk.Sheets("60 Days").Range("A" & x + 1).Value
CardMemName = Left(Trim(CardMemName), 1)
ExcelWbk.Sheets("60 Days").Range("Z" & x + 1).Formula = "=RIGHT(A" & x + 1 & ",LEN(A" & x + 1 & ")-FIND(""#"",SUBSTITUTE(A" & x + 1 & ","" "",""#"",LEN(A" & x + 1 & ")-LEN(SUBSTITUTE(A" & x + 1 & ","" "",""""))),1))"
ExcelWbk.Sheets("60 Days").Range("Z" & x + 1).Copy
ExcelWbk.Sheets("60 Days").Range("Z" & x + 1).PasteSpecial xlPasteValues
CardMemName = CardMemName & " " & ExcelWbk.Sheets("60 Days").Range("Z" & x + 1).Value
wdDoc.Close
problem is that it should consider DOCFilenm as active doc ,however if any xyz word doc was open before running the macro it consider that file as active instead of DOCFilenm