Running Mailmerge more than one time - excel

so I have the code bellow (its macro sending emails with mail merge from excel file) and when I run it for the first time it's OK but if I run it for the second time I'm getting the 462 (The remove server machine does not exist or is unavailable). I know that this is caused by occupied variable. But I did everything that I know to prevent this. Could someone tell me how to adjust my code so it can run multiple times without closing the file?
Sub Send_Emails()
Application.ScreenUpdating = False
Dim wrd As Word.Application
Dim Doc1 As Document, Doc2 As Document, Doc3 As Document, Doc4 As Document
Dim StrDoc As String, ListOfDocuments As String
Set wrd = CreateObject("Word.Application")
ListOfDocuments = ThisWorkbook.Path & "\Templates\Germany\Supervisors\ListOfDocuments.docx"
Set Doc1 = wrd.Documents.Open(ListOfDocuments)
With Doc1.MailMerge
If .State = wdMainAndDataSource Then
.Destination = wdSendToNewDocument
.Execute
End If
End With
Set Doc2 = ActiveDocument
ActiveDocument.SaveAs (ThisWorkbook.Path & "\Templates\Germany\Supervisors\Recipients.docx")
Call EmailMergeTableMaker(Doc2)
With Doc2
.SaveAs (ThisWorkbook.Path & "\Templates\Germany\Supervisors\Recipients.docx")
End With
Set Doc3 = Documents.Open(Filename:=ThisWorkbook.Path & "\Templates\Germany\Supervisors\SupervisorEmail.docx", _
AddToRecentFiles:=False)
With Doc3.MailMerge
.MainDocumentType = wdEMail
.OpenDataSource Name:=(ThisWorkbook.Path & "\Templates\Germany\Supervisors\Recipients.docx"), ConfirmConversions:=False, ReadOnly:=False, _
LinkToSource:=True, AddToRecentFiles:=False, Connection:="", SQLStatement:="", _
SQLStatement1:="", SubType:=wdMergeSubTypeOther
If .State = wdMainAndDataSource Then
.Destination = wdSendToNewDocument
.Execute
End If
End With
ActiveDocument.SaveAs (ThisWorkbook.Path & "\Templates\Germany\Supervisors\EmailsToSend.docx")
Set Doc4 = Documents.Open(ThisWorkbook.Path & "\Templates\Germany\Supervisors\EmailsToSend.docx")
Doc3.Close SaveChanges:=False
Set Doc3 = Nothing
Call SendEmailsOutlook
Doc1.Close SaveChanges:=False
Doc2.Close SaveChanges:=False
Doc4.Close SaveChanges:=False
Set Doc1 = Nothing
Set Doc2 = Nothing
Set Doc4 = Nothing
wrd.Quit
Set wrd = Nothing
Application.ScreenUpdating = True
'ThisWorkbook.Close
ThisWorkbook.Saved = True
'Application.Quit
End Sub
Sub SendEmailsOutlook()
Dim oItem As Outlook.MailItem
Dim j As Long
Dim oAccount As Outlook.Account
Dim Source As Document, MailList As Document
Dim Recipient As String, MailListDocument As String, SourceDocument As String
MailListDocument = ThisWorkbook.Path & "\Templates\Germany\Supervisors\Recipients.docx"
SourceDocument = ThisWorkbook.Path & "\Templates\Germany\Supervisors\EmailsToSend.docx"
Set MailList = Documents.Open(MailListDocument)
Set Source = Documents.Open(SourceDocument)
For j = 1 To Source.Sections.Count - 1
Set oItem = CreateObject("Outlook.Application").CreateItem(olMailItem)
For Each oAccount In Outlook.Application.Session.Accounts
If oAccount = "xxxxxx" Then 'xxxxxx
With oItem
'.SentOnBehalfOfName = "xxxxxx"
'.Attachments.Add ThisWorkbook.Path & "xxxxxx"
.Subject = "xxxxxx"
.HTMLBody = Source.Sections(j).Range.Text
Recipient = Left(MailList.Tables(1).Cell(j + 1, 1).Range.Text, Len(MailList.Tables(1).Cell(j + 1, 1).Range.Text) - 1)
If Len(Recipient) < 3 Then Exit For
.SendUsingAccount = oAccount
.To = "xxxxxx"
'.To = Recipient
.Send
End With
Set oItem = Nothing
End If
Next
Next j
End Sub
Sub EmailMergeTableMaker(DocName As Document)
Dim oTbl As Object
Dim i As Integer, j As Integer
Dim oRow As Object
Dim oRng As Object
Dim strTxt As String
With DocName
.Paragraphs(1).Range.Delete
Call TableJoiner
For Each oTbl In .Tables
j = 4
With oTbl
i = .Columns.Count - j
For Each oRow In .Rows
Set oRng = oRow.Cells(j).Range
With oRng
.MoveEnd Unit:=wdCell, Count:=i
.Cells.Merge
strTxt = Replace(.Text, vbCr, vbTab)
On Error Resume Next
If Len(strTxt) > 1 Then .Text = Left(strTxt, Len(strTxt) - 2)
End With
Next
End With
Next
For Each oTbl In .Tables
For i = 1 To j
oTbl.Columns(i).Cells.Merge
Next
Next
With .Tables(1)
.Rows.Add BeforeRow:=.Rows(1)
.Cell(1, 1).Range.Text = "Recipient"
.Cell(1, 2).Range.Text = "Name"
.Cell(1, 3).Range.Text = "Gender"
.Cell(1, 4).Range.Text = "List"
End With
.Paragraphs(1).Range.Delete
Call TableJoiner
End With
Set oRng = Nothing
End Sub
Private Sub TableJoiner()
Dim wrd2 As Object, doc As Object, tbl As Object
Dim oTbl As Table
Set wrd2 = GetObject(, "Word.Application")
Set doc = wrd2.Documents.Open(ThisWorkbook.Path & "\Templates\Germany\Supervisors\Recipients.docx")
For Each tbl In doc.Tables
With tbl.Range.Next
If .Information(wdWithInTable) = False Then .Delete
End With
Next
Set wrd = Nothing
End Sub
Thank for any suggestions!

Related

VBA Excel to Word Content Control Running Slowly

I have a simple interface in Excel that allows the user to export a table from Excel to Word as a new or existing document. It then loops through the last column(8) in the word table and inserts a drop down list in each cell.
The code does what it is supposed to do but runs slowly when inserting the content controls. Additionally, I can see it insert each content control in MS Word which tells me that screen updating is not disabled in Word. Any suggestions to make my code to run faster?
Full code and reference word table below.
Sub ExportToWord()
Dim ws As Excel.Worksheet
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim objRange As Word.Range
Dim newDoc As Boolean
Dim rng As Excel.Range
Dim lRow As Integer, s As Integer
Dim objCC As ContentControl
Dim counter As Long
Dim oRow As Row
If UF_Load.check_new = True Then
newDoc = True
Else
newDoc = False
End If
Set ws = ThisWorkbook.Sheets("UI")
Application.ScreenUpdating = False
Application.EnableEvents = False
s = ws.Range("rng_demo").Row - 2
c = ws.Range("rng_demo").Column
lRow = ws.Cells(Rows.Count, s).End(xlUp).Row
Set rng = ws.Range("A" & s).Resize(lRow, 8)
rng.Copy
If wrdApp Is Nothing Then
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If Err.Number > 0 Then Set wrdApp = CreateObject("Word.Application")
On Error GoTo 0
End If
'Handle if Word Application is not found
If Err.Number <> 0 Then GoTo SafeExit:
'MsgBox "Microsoft Word document could not be found, aborting", vbExclamtion, "Microsoft Word Error 429"
'GoTo SafeExit:
'End If
On Error GoTo 0
'Make MS Word Visible and Active
wrdApp.Activate
wrdApp.Visible = True
If newDoc = True Then
Set wrdDoc = wrdApp.Documents.Add 'create as new word document
'Set as editable
If wrdDoc.ActiveWindow.View.SplitSpecial = wdPaneNone Then
wrdDoc.ActiveWindow.ActivePane.View.Type = wdPrintView
Else
wrdDoc.ActiveWindow.View.Type = wdPrintView
End If
'Copy table data to word doc
Set tbl = rng
tbl.Copy
'Paste Table into Word doc
wrdDoc.Paragraphs(1).Range.PasteExcelTable _
LinkedToExcel:=False, _
WordFormatting:=False, _
RTF:=False
'Autofit table to Word doc
Set Wordtable = wrdDoc.Tables(1)
Wordtable.AutoFitBehavior (wdAutoFitWindow)
'Dim oRng As Range
'Loop through last table column and add Combobox
'Insert comboboxes
With Wordtable
counter = 0
For Each oRow In Wordtable.Rows
'Set oRng = oRow.Cells(1).Range
'If Trim(Len(oRow.Cells(1).Range.Text)) <> " " Then
If Len(Trim(Replace(oRow.Cells(1).Range.Text, Chr(160), ""))) <> 2 And counter >= 8 Then 'GoTo Nexti:
On Error Resume Next
Set objCC = wrdApp.ActiveDocument.ContentControls.Add(wdContentControlDropdownList, oRow.Cells(8).Range)
If Err.Number = 5941 Then GoTo Nexti:
objCC.Title = "Interpretation"
If objCC.ShowingPlaceholderText Then
objCC.SetPlaceholderText , , "-"
objCC.DropdownListEntries.Add "Valid"
objCC.DropdownListEntries.Add "Significant Difference"
objCC.DropdownListEntries.Add "WNL"
objCC.DropdownListEntries.Add "Slightly Below Expectations"
objCC.DropdownListEntries.Add "Below Expectations"
objCC.DropdownListEntries.Add "Far Below Expectations"
Debug.Print Len(oRow.Cells(7).Range.Text)
End If
Else
'Do nothing
End If
Nexti:
On Error GoTo 0
counter = counter + 1
Next
End With
On Error GoTo SafeExit:
Else
'or open an existing document
Set wrdDoc = wrdApp.Documents.Open(filepath, , False) 'wrdApp.Documents.Open("C:\Users\Apache Paint\Desktop\Clients\Stephen Schmitz\TestDocument.docx")
'Set as editable
If wrdDoc.ActiveWindow.View.SplitSpecial = wdPaneNone Then
wrdDoc.ActiveWindow.ActivePane.View.Type = wdPrintView
Else
wrdDoc.ActiveWindow.View.Type = wdPrintView
End If
'Copy table data to word doc
With wrdDoc
Set tbl1 = .Tables.Add(Range:=wrdDoc.Paragraphs.Last.Range, _
NumRows:=1, NumColumns:=8, _
AutoFitBehavior:=wdAutoFitWindow) 'autofit content 'DefaultTableBehavior:=wdWord9TableBehavior,
With tbl1
.PreferredWidthType = wdPreferredWidthPercent
.PreferredWidth = 100
End With
Set tbl = rng
Set objRange = wrdDoc.Content
With objRange
.Collapse Direction:=0 'wdCollapseEnd
'.InsertAfter vbCrLf '<<< Error on line
.Collapse Direction:=0
.InsertBreak Type:=wdPageBreak
.Paste '<< paste the table
End With
'Autofit the document
Set Wordtable = objRange.Tables(1) 'Set Wordtable = objRange.Tables(1)
Wordtable.AutoFitBehavior (wdAutoFitWindow)
With Wordtable
.PreferredWidthType = wdPreferredWidthPercent
.PreferredWidth = 100
'Insert comboboxes
counter = 0
For Each oRow In Wordtable.Rows
Set oRng = oRow.Cells(1).Range
If Len(Trim(Replace(oRow.Cells(1).Range.Text, Chr(160), ""))) <> 2 And counter >= 8 Then 'GoTo Nexti:
On Error Resume Next
Set objCC = wrdApp.ActiveDocument.ContentControls.Add(wdContentControlDropdownList, oRow.Cells(8).Range)
If Err.Number = 5941 Then GoTo Nexti2:
objCC.Title = "Interpretation"
If objCC.ShowingPlaceholderText Then
objCC.SetPlaceholderText , , "-"
objCC.DropdownListEntries.Add "Valid"
objCC.DropdownListEntries.Add "Significant Difference"
objCC.DropdownListEntries.Add "WNL"
objCC.DropdownListEntries.Add "Slightly Below Expectations"
objCC.DropdownListEntries.Add "Below Expectations"
objCC.DropdownListEntries.Add "Far Below Expectations"
Debug.Print Len(oRow.Cells(7).Range.Text)
End If
Else
'Do nothing
End If
Nexti2:
On Error GoTo 0
counter = counter + 1
Next
End With
End With
filepath = ""
End If
SafeExit:
If Err.Number <> 0 Then
Beep
MsgBox "Microsoft Excel has encountered an error and could not complete the Export to MS Word. Possible reasons are:" & vbNewLine & vbNewLine & _
"-Reference to Microsoft Word Object Library is not enabled" & vbNewLine & vbNewLine & "-The document opened in Read Only mode" & vbNewLine & vbNewLine & _
"-Code execution was interrupted because the was closed or altered during execution" & vbNewLine & vbNewLine & "-Document is already open in MS Word" _
, vbCritical, "Error"
End If
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.CutCopyMode = False
End Sub
It seems to me your code could be made both more efficient and shorter:
Sub ExportToWord()
Application.ScreenUpdating = False: Application.EnableEvents = False
Dim ws As Excel.Worksheet, rng As Excel.Range, lRow As Long, c As Long, r As Long, newDoc As Boolean
Dim wrdApp As Word.Application, wrdDoc As Word.Document, wrdTbl As Word.Table, wrdCCtrl As Word.ContentControl
Const filepath As String = "C:\Users\Apache Paint\Desktop\Clients\Stephen Schmitz\TestDocument.docx"
Set ws = ThisWorkbook.Sheets("UI")
With ws
c = .Range("rng_demo").Column
r = .Range("rng_demo").Row - 2
lRow = .Cells(.Rows.Count, c).End(xlUp).Row
Set rng = .Range("A" & r).Resize(lRow, 8)
End With
If wrdApp Is Nothing Then
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If Err.Number > 0 Then Set wrdApp = CreateObject("Word.Application")
On Error GoTo 0
End If
With wrdApp
.Visible = True
If UF_Load.check_new = True = True Then
'create as new word document
Set wrdDoc = wrdApp.Documents.Add
'create a table
Set wrdTbl = wrdDoc.Tables.Add(Range:=wrdDoc.Paragraphs.Last.Range, NumRows:=1, NumColumns:=8)
Else
'open an existing document
Set wrdDoc = .Open(filepath, , False)
'copy & paste the Excel table
rng.Copy
Set wrdTbl = wrdDoc.Paragraphs.Last.Range.PasteExcelTable(LinkedToExcel:=False, WordFormatting:=False, RTF:=False)
End If
With wrdDoc
With wrdTbl
'format the table
.PreferredWidthType = wdPreferredWidthPercent
.PreferredWidth = 100
'Insert comboboxes
For r = 9 To .Rows.Count
If r = 9 Then
Set wrdCCtrl = wrdDoc.ContentControls.Add(wdContentControlDropdownList, .Cell(r, 8).Range)
With wrdCCtrl
.Title = "Interpretation"
.SetPlaceholderText , , "-"
.DropdownListEntries.Add "Valid"
.DropdownListEntries.Add "Significant Difference"
.DropdownListEntries.Add "WNL"
.DropdownListEntries.Add "Slightly Below Expectations"
.DropdownListEntries.Add "Below Expectations"
.DropdownListEntries.Add "Far Below Expectations"
End With
Else
.Cell(r, 8).Range.FormattedText = wrdCCtrl.Range.FormattedText
End If
Next
End With
End With
End With
Application.ScreenUpdating = True: Application.EnableEvents = True: Application.CutCopyMode = False
End Sub

Match first row of first column if matched then send its corresponding row of second column into Word document

I am having an excel with two columns Requirement and Source. I have another Word document with Requirement which are there in excel. I want it to be matched. If it is matched then its corresponding source need to be sent to Requirement in word document.
The excel file data:
In the word document the data should be displayed like this:
enter image description here
I tried in this way:
Sub SearchItem()
Dim shtSearchItem As Worksheet
Dim shtExtract As Worksheet
Dim oWord As Word.Application
Dim WordNotOpen As Boolean
Dim oDoc As Word.Document
Dim oRange As Word.Range
Dim LastRow As Long
Dim CurrRowShtSearchItem As Long
Dim CurrRowShtExtract As Long
Dim myPara As Long
On Error Resume Next
Set oWord = GetObject(, "Word.Application")
If Err Then
Set oWord = New Word.Application
WordNotOpen = True
End If
On Error GoTo Err_Handler
oWord.Visible = True
oWord.Activate
Set oDoc = oWord.Documents.Open("File Location")
Set shtSearchItem = ThisWorkbook.Worksheets(1)
If ThisWorkbook.Worksheets.Count < 2 Then
ThisWorkbook.Worksheets.Add After:=shtSearchItem
End If
Set shtExtract = ThisWorkbook.Worksheets(2)
LastRow = shtSearchItem.UsedRange.Rows(shtSearchItem.UsedRange.Rows.Count).Row
For CurrRowShtSearchItem = 2 To LastRow
Set oRange = oDoc.Range
With oRange.Find
.Text = shtSearchItem.Cells(CurrRowShtSearchItem, 1).Text
.MatchCase = False
.MatchWholeWord = True
While oRange.Find.Execute = True
oRange.Select
If .Found Then
oRange.InsertAfter ("Reference" & ":") ' <= what need to be done?
End If
oRange.Start = oRange.End
oRange.End = ActiveDocument.Range.End
oRange.Collapse wdCollapseEnd
Wend
End With
Next CurrRowShtSearchItem
If WordNotOpen Then
oWord.Quit
End If
'Release object references
Set oWord = Nothing
Set oDoc = Nothing
Exit Sub
Err_Handler:
MsgBox "Word caused a problem. " & Err.Description, vbCritical, "Error: " & Err.Number
If WordNotOpen Then
oWord.Quit
End If
End Sub
Please Help. Thank You
Try something based on:
Sub SendRefsToDoc()
'Note: A reference to the Word library must be set, via Tools|References
Dim wdApp As New Word.Application, wdDoc As Word.Document, StrNm As String
Dim r As Long, xlFList As String, xlRList As String
StrNm = "C:\Users\" & Environ("UserName") & "\Documents\MyDocument.docx"
If Dir(StrNm) <> "" Then
With Worksheets("Sheet1")
For r = 2 To .Cells(.Rows.Count, 1).End(xlUp).Row
If .Range("A" & r).Text = "" Then
xlRList = xlRList & ", " & Trim(.Range("B" & r))
Else
xlFList = xlFList & "|" & Trim(.Range("A" & r))
xlRList = xlRList & "|" & Trim(.Range("B" & r))
End If
Next
End With
With wdApp
.Visible = False
Set wdDoc = Documents.Open(Filename:=StrNm, AddToRecentFiles:=False, Visible:=False)
With wdDoc
For r = 1 To UBound(Split(xlFList, "|"))
With .Range
With .Find
.Replacement.ClearFormatting
.Text = Split(xlFList, "|")(r)
.Replacement.Text = ""
.Forward = True
.Format = False
.Wrap = wdFindStop
End With
Do While .Find.Execute
.Paragraphs.First.Range.Characters.Last.InsertBefore vbCr _
& "Reference: " & Split(xlRList, "|")(r)
With .Paragraphs.First.Range.Font
.Bold = True
.Italic = True
End With
With .Paragraphs.Last.Range.Font
.Bold = False
.Italic = False
End With
.Collapse wdCollapseEnd
Loop
End With
Next
.Close True
End With
.Quit
End With
Else
MsgBox "File not found: " & vbCr & StrNm, vbExclamation
End If
Set wdDoc = Nothing: Set wdApp = Nothing
End Sub

Word Macro object variable or with block variable not set on alternate run

I have written a macro that would bring values of certain field from a word file and insert it in a excel file. On every alternate run the word macro gives an error "object variable or with block variable not set". Please help me.
Sub getWordFormData()
Dim exApp As Object, myDoc As Object
Dim myFolder As String, strFile As String
Dim excelApp As Object
Dim openExcel As Workbook
myFolder = ActiveDocument.Path
If Len((myFolder)) = 0 Then
MsgBox myFolder & vbCrLf & "Not Found", vbInformation, "Cancelled - getWordFormData"
End If
Application.ScreenUpdating = False
Set exApp = CreateObject("Word.Application")
Set myDoc = ActiveWorkbook
Set excelApp = New Excel.Application
Set openExcel = excelApp.Workbooks.Open("F:\VBA Sample projects\word to excel\Proposal_DB.xlsx")
excelApp.Visible = True
excelApp.Range("A1").End(xlDown).Offset(1, 0).Select
Set myDoc = exApp.Documents.Open(FileName:=myFolder & "\" & "TEMPLATE WORD.docx", ReadOnly:=True, AddToRecentFiles:=False, Visible:=False)
With excelApp
.Cells(ActiveCell.Row, 1).Value = myDoc.SelectContentControlsByTag("date").Item(1).Range.Text
.Cells(ActiveCell.Row, 2).Value = myDoc.SelectContentControlsByTag("ProtocolNo.").Item(1).Range.Text
.Cells(ActiveCell.Row, 3).Value = myDoc.SelectContentControlsByTag("Subject").Item(1).Range.Text
'excelApp.Cells(ActiveCell.Row, 4).Value = myDoc.SelectContentControlsByTag("companyname").Item(1).Range.Text
'excelApp.Cells(ActiveCell.Row, 5).Value = myDoc.SelectContentControlsByTag("customer_name").Item(1).Range.Text
'excelApp.Cells(Nextrow.Row, 6).Value = myDoc.SelectContentControlsByTag("total_amount").Item(1).Range.Text
'excelApp.Cells(Nextrow.Row, 7).Value = myDoc.SelectContentControlsByTag("employee_name").Item(1).Range.Text
End With
myDoc.Close SaveChanges:=False
' strFile = Dir()
'Wend
excelApp.Quit
Application.ScreenUpdating = True
'End With
'exApp.Quit
End Sub
Compiled but not tested:
'add a reference to the Microsoft Excel objectl ibary in your VBA project
Sub getWordFormData()
Dim myDoc As Document
Dim myFolder As String, strFile As String
Dim excelApp As Excel.Application
Dim excelWb As Excel.Workbook, rw As Excel.Range
myFolder = ActiveDocument.Path
If Len(myFolder) = 0 Then
MsgBox myFolder & vbCrLf & " Not Found", vbInformation, "Cancelled - getWordFormData"
Exit Sub
End If
'create Excel application and open the workbook
Set excelApp = New Excel.Application
excelApp.Visible = True
Set excelWb = excelApp.Workbooks.Open("F:\VBA Sample projects\word to excel\Proposal_DB.xlsx")
'get the next empty row in the worksheet
With excelWb.Sheets(1) '<< or use a specific sheet name
Set rw = .Cells(.Rows.Count, 1).End(xlUp).Offset(1, 0).EntireRow
End With
'you don't need a separate Word instance to open this document...
Set myDoc = Documents.Open(FileName:=myFolder & "\" & "TEMPLATE WORD.docx", _
ReadOnly:=True, AddToRecentFiles:=False, Visible:=False)
rw.Cells(1).Value = myDoc.SelectContentControlsByTag("date").Item(1).Range.Text
rw.Cells(2).Value = myDoc.SelectContentControlsByTag("ProtocolNo.").Item(1).Range.Text
rw.Cells(3).Value = myDoc.SelectContentControlsByTag("Subject").Item(1).Range.Text
myDoc.Close savechanges:=False
excelWb.Close savechanges:=True
excelApp.Quit
End Sub

How do I transfer formatted text from Word to Excel?

The below code is copied data from MS Word (content control) to Excel. However, when I copy text with bullet and paste into Excel, it removes the bullets and pastes the text only.
How can I copy bullets from the content control?
Sub getWordFormData()
Dim wdApp As New Word.Application
Dim myDoc As Word.Document
Dim CCtl As Word.ContentControl
Dim myFolder As String, strFile As String
Dim myWkSht As Worksheet, i As Long, j As Long
myFolder = "enter folder path" '<< enter you folder path for the word document
If Dir(myFolder & "\" & "*.*") = "" Then
Application.ScreenUpdating = True
MsgBox "The folder is empty."
Exit Sub
End If
Set myWkSht = ActiveSheet
ActiveSheet.Cells.Clear
Range("A1") = "Test 1"
Range("B1") = "Test 2"
Range("A1:B1").Font.Bold = True
i = myWkSht.Cells(myWkSht.Rows.Count, 1).End(xlUp).Row
strFile = Dir(myFolder & "\*.docx", vbNormal)
While strFile <> ""
i = i + 1
Set myDoc = wdApp.Documents.Open(Filename:=myFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With myDoc
j = 0
For Each CCtl In .ContentControls
j = j + 1
myWkSht.Cells(i, j) = CCtl.Range.Text
Next
myWkSht.Columns.AutoFit
End With
myDoc.Close SaveChanges:=False
strFile = Dir()
Wend
wdApp.Quit
Set myDoc = Nothing: Set wdApp = Nothing: Set myWkSht = Nothing
Application.ScreenUpdating = True
End Sub
try with this block
With myDoc
j = 0
For Each CCtl In .ContentControls
j = j + 1
CCtl.Range.Copy
myWkSht.Cells(i, j).PasteSpecial Paste:=xlPasteValues
Next
myWkSht.Columns.AutoFit
End With

export email from outlook

Could you advise please how to export emails from excel files?
I have an excel files with column called emails - this is a list of emails.
How can VBA script check every email from excel file in outlook and export emails with subject, data, sender from these excel file to new excel file or new sheet in current excel.
I have this script:
Const MACRO_NAME = "Export Messages to Excel (Rev 4)"
Sub ExportMessagesToExcelbyDate()
Dim olkLst As Object, _
olkMsg As Object, _
excApp As Object, _
excWkb As Object, _
excWks As Object, _
intRow As Integer, _
intVersion As Integer, _
strFilename As String, _
strDateRange As String, _
arrTemp As Variant, _
datStart As Date, _
datEnd As Date
strFilename = InputBox("Enter a filename to save the exported messages to.", , MICRO_NAME)
If strFilename <> "" Then
strDateRange = InputBox("Enter the date range of the messages to export in the form ""mm/dd/yyyy to mm/dd/yyyy""", MACRO_NAME, Date & " to " & Date)
arrTemp = Split(strDateRange, "to")
datStart = IIf(IsDate(arrTemp(0)), arrTemp(0), Date) & " 12:00am"
datEnd = IIf(IsDate(arrTemp(1)), arrTemp(1), Date) & " 11:59pm"
intVersion = GetOutlookVersion()
Set excApp = CreateObject("Excel.Application")
Set excWkb = excApp.Workbooks.Add()
Set excWks = excWkb.ActiveSheet
'Write Excel Column Headers
With excWks
.Cells(1, 1) = "Subject"
.Cells(1, 2) = "Received"
.Cells(1, 3) = "Sender"
End With
intRow = 2
'Write messages to spreadsheet
Set olkLst = Application.ActiveExplorer.CurrentFolder.Items.Restrict("[ReceivedTime] >= '" & Format(datStart, "ddddd h:nn AMPM") & "'" & " AND [ReceivedTime] <= '" & Format(datEnd, "ddddd h:nn AMPM") & "'")
For Each olkMsg In olkLst
'Only export messages, not receipts or appointment requests, etc.
If olkMsg.Class = olMail Then
'Add a row for each field in the message you want to export
excWks.Cells(intRow, 1) = olkMsg.Subject
excWks.Cells(intRow, 2) = olkMsg.ReceivedTime
excWks.Cells(intRow, 3) = GetSMTPAddress(olkMsg, intVersion)
intRow = intRow + 1
End If
Next
Set olkMsg = Nothing
excWkb.SaveAs strFilename
excWkb.Close
End If
Set olkLst = Nothing
Set excWks = Nothing
Set excWkb = Nothing
Set excApp = Nothing
MsgBox "Process complete. A total of " & intRow - 2 & " messages were exported.", vbInformation + vbOKOnly, MICRO_NAME
End Sub
Private Function GetSMTPAddress(Item As Outlook.MailItem, intOutlookVersion As Integer) As String
Dim olkSnd As Outlook.AddressEntry, olkEnt As Object
On Error Resume Next
Select Case intOutlookVersion
Case Is < 14
If Item.SenderEmailType = "EX" Then
GetSMTPAddress = SMTP2007(Item)
Else
GetSMTPAddress = Item.SenderEmailAddress
End If
Case Else
Set olkSnd = Item.Sender
If olkSnd.AddressEntryUserType = olExchangeUserAddressEntry Then
Set olkEnt = olkSnd.GetExchangeUser
GetSMTPAddress = olkEnt.PrimarySmtpAddress
Else
GetSMTPAddress = Item.SenderEmailAddress
End If
End Select
On Error GoTo 0
Set olkPrp = Nothing
Set olkSnd = Nothing
Set olkEnt = Nothing
End Function
Function GetOutlookVersion() As Integer
Dim arrVer As Variant
arrVer = Split(Outlook.Version, ".")
GetOutlookVersion = arrVer(0)
End Function
Function SMTP2007(olkMsg As Outlook.MailItem) As String
Dim olkPA As Outlook.PropertyAccessor
On Error Resume Next
Set olkPA = olkMsg.PropertyAccessor
SMTP2007 = olkPA.GetProperty("http://schemas.microsoft.com/mapi/proptag/0x5D01001E")
On Error GoTo 0
Set olkPA = Nothing
End Function
But this script export only selected folder in outlook.
What is the more important it should be exported from conversation history. For example in excel file there is mailbox YourMailbox#gmail.com. Script should find all conversation history and emails with this person and export information from emails. Information such as Subject, sender, date. Also script should check all list emails from excel file, not one.
Thanks for advices.
Application.ActiveExplorer.CurrentFolder will get current select folder, If you want to get all folder, you could refer to the below code:
Option Explicit
Sub repopulate3()
Dim olApp As Outlook.Application
Dim olNs As Outlook.Namespace
Dim olparentfolder As Outlook.Folder
Dim olMail As Object
Dim eFolder As Object
Dim i As Long
Dim wb As Workbook
Dim ws As Worksheet
Dim iCounter As Long
Dim lrow As Long
Dim lastrow As Long
'Set wb = ActiveWorkbook
'Set ws = wb.Worksheets("vlookup")
On Error Resume Next
Set olApp = GetObject(, "Outlook.Application")
On Error GoTo 0
If olApp Is Nothing Then
Set olApp = CreateObject("Outlook.Application")
End If
Set olNs = olApp.GetNamespace("MAPI")
Set olparentfolder = olNs.GetDefaultFolder(olFolderInbox)
'wb.Sheets("vlookup").range("A2:C500").ClearContents
'i think you want column E here, not L?
'lastrow = ThisWorkbook.Worksheets("vlookup").Cells(Rows.count, "E").End(xlUp).Row
ProcessFolder olparentfolder
ExitRoutine:
Set olparentfolder = Nothing
Set olNs = Nothing
Set olApp = Nothing
End Sub
Private Sub ProcessFolder(ByVal oParent As Outlook.Folder)
Dim olFolder As Outlook.Folder
Dim olMail As Object
Dim i As Long
Dim wb As Workbook
Dim ws As Worksheet
Dim iCounter As Long
Dim lrow As Long
Dim lastrow As Long
'Set wb = ActiveWorkbook
'Set ws = wb.Worksheets("vlookup")
'lastrow = ThisWorkbook.Worksheets("vlookup").Cells(Rows.count, "E").End(xlUp).Row
For i = oParent.Items.Count To 1 Step -1
Debug.Print oParent
If TypeOf oParent.Items(i) Is MailItem Then
Set olMail = oParent.Items(i)
Debug.Print " " & olMail.Subject
Debug.Print " " & olMail.ReceivedTime
Debug.Print " " & olMail.SenderEmailAddress
Debug.Print
'For iCounter = 2 To lastrow
'If InStr(olMail.SenderEmailAddress, ws.Cells(iCounter, 5).Value) > 0 Then 'qualify the cell
'With ws
' lrow = .range("A" & .Rows.count).End(xlUp).Row
' .range("C" & lrow + 1).Value = olMail.body
' .range("B" & lrow + 1).Value = olMail.ReceivedTime
' .range("A" & lrow + 1).Value = olMail.SenderEmailAddress
'End With
'End If
'Next iCounter
End If
Next i
If (oParent.Folders.Count > 0) Then
For Each olFolder In oParent.Folders
ProcessFolder olFolder
Next
End If
End Sub
For more information, Please refer to the below link:
VBA code to loop through every folder and subfolder in Outlook

Resources