The goal is to replace the last line of a document. The last line always starts with a $. I am using a find here but don't have to, I couldn't get any other way to function.
I have used replace.text successfully within find but due to some conditions I can't use that without tons of if statements running different Finds.
Everything seems to be working I try except for going to the end of the page or expanding to delete/replace the entire line after the $.
Specifically the .Expand function doesn't work for me the 10 different ways I've tried. and .EndKeys never works for me. (I have tried every combination of WordDoc.Expand WordApp.Expand WordSelection.Expand setting activedocument etc.)
The code is a bit of a mess at this point. The For Each oRange is the only part with issues and is my 10th iteration of trying to get it to work by now.
Sub OpenDoc()
Dim strFile As String
Dim strPN As String
Dim WordApp As Object, WordDoc As Object
Dim WordSelection As Object
Const wdReplaceOne = 1
Dim oRange As Object
Dim RoundPrice As Integer
Dim PriceString As String
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
For i = Selection.Rows.Count To 1 Step -1
If Cells(i, 4).Value <> "" Then
If Cells(i, 4).Value <> "PN" Then
'Print SD
If IsError(Cells(i, 28).Value) = True Then
RoundPrice = Cells(i, 12).Value
RoundPrice = RoundPrice * 0.85
PriceString = RoundPrice
PriceString = Left(PriceString, Len(PriceString) - 1)
PriceString = PriceString & "9"
strPN = Cells(i, 4).Value
strFile = "c:\Users\Robert\Desktop\Masterlist\B_" & strPN & ".docx" 'change to path of your file
If Dir(strFile) <> "" Then 'First we check if document exists at all at given location
'Word session creation
Set WordApp = CreateObject("Word.Application")
'word will be closed while running
WordApp.Visible = True
'open the .doc file
Set WordDoc = WordApp.Documents.Open(strFile)
'WordDoc.PrintOut
Set WordSelection = WordApp.Selection
For Each oRange In WordDoc.StoryRanges
With oRange.Find
.Forward = False
.Text = "$"
.Execute Find
End With
With WordSelection
.Expand Unit:=wdLine
.Text = "$" & PriceString
End With
Next oRange
WordDoc.SaveAs ("c:\Users\Robert\Desktop\B" & "_" & strPN & ".docx")
WordApp.Quit
End If
End If
End If
End If
Next i
End Sub
Your code isn't working because WordSelection doesn't get moved after the Set statement. You can accomplish what you need just using the Range. You should also check that Find actually found something.
For Each oRange In WordDoc.StoryRanges
With oRange
With .Find
.Forward = False
.Text = "$"
End With
If .Find.Execute Then
.Expand Unit:=wdParagraph
.Text = "$" & PriceString
End If
End With
Next oRange
You should also get rid of the late binding as you gain nothing at all by using it. Instead set a reference to the Word object library and declare the objects properly. That way you will also have the benefit of Intellisense.
Related
I'm trying do generate some files docx of data from excel to word.
I'm just learning the basic of VBA, so I lasted a few hours to find this a find and replace logical. But at the time I tried with a lot of text, more than 255 characteres it's not worked well.
Maybe you can find some simple solution.
This is the code abelow:
Sub gera_plano()
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
Set arqPlanos = objWord.Documents.Open(ThisWorkbook.Path & "\Modelo de Plano de Aula
(macro).docx")
Set conteudoDoc = arqPlanos.Application.Selection
For colTab = 1 To 20
conteudoDoc.Find.Text = Cells(1, colTab).Value
conteudoDoc.Find.Replacement.Text = Cells(2, colTab).Value
conteudoDoc.Find.Execute Replace:=wdReplaceAll
Next
arqPlanos.SaveAs2 (ThisWorkbook.Path & "\Planos\Aula - " & Cells(2, 3).Value & " -T" & Cells(2,
1).Value & ".docx")
arqPlanos.Close
objWord.Quit
Set arqPlanos = Nothing
Set conteudoDoc = Nothing
Set objWord = Nothing
MsgBox ("Plano gerado com sucesso!")
End Sub
Thank you very much for your helop
Modified, your macro would look like:
Sub gera_plano()
' Note: The following code requires a reference to the
' MS Forms 2.0 Object Library, set in the VBE via Tools|References
' typically found in: C:\Windows\System32; or
' C:\Program Files (x86)\Microsoft Office\root\vfs\SystemX86
Dim objWord As Object, arqPlanos As Object, MyData As DataObject, strFnd As String
Set objWord = CreateObject("Word.Application")
Set MyData = New DataObject
Set arqPlanos = objWord.Documents.Open(ThisWorkbook.Path & "\Modelo de Plano de Aula(macro).docx")
With arqPlanos
For colTab = 1 To 20
strFnd = Cells(1, colTab).Text
MyData.SetText Cells(2, colTab).Text
MyData.PutInClipboard
With .Find
.MatchWildcards = True
.Text = strFnd
.Replacement.Text = "^c"
.Execute Replace:=wdReplaceAll
End With
Next
.SaveAs2 (ThisWorkbook.Path & "\Planos\Aula - " & Cells(2, 3).Value & " -T" & Cells(2, 1).Value & ".docx")
.Close
End With
objWord.Quit
Set arqPlanos = Nothing: Set objWord = Nothing
MsgBox ("Plano gerado com sucesso!")
End Sub
You would still need to do the work to convert the longer strings, especially, to the wildcard format. The links below explain how to use wildcards:
https://wordmvp.com/FAQs/General/UsingWildcards.htm
https://support.microsoft.com/en-us/office/examples-of-wildcard-characters-939e153f-bd30-47e4-a763-61897c87b3f4
I have a Word document containing a few lines of text and a table with many place holders I will fill in from Excel later in the same document but saving it as PDF.
My final goal is to duplicate the whole text in the word file as it is before any modification and paste it every time I have to complete it with the values in the Excel file.
Inside word VBA, this works perfectly. Copy the whole document and past it at the end, duplicating the table and the lines of text.
Selection.WholeStory
Selection.Copy
Selection.MoveDown Unit:=wdParagraph, Count:=2
Selection.PasteAndFormat (wdFormatOriginalFormatting)
And in Excel VBA, I have this working just fine. Except the * Asterics part, I don't know how to execute the code that works in Word VBA from Excel VBA.
Sub GenerateDoc()
DocLoc = Application.ActiveWorkbook.Path & "\CategoryTable2.docx"
'Open Word Template
With Sheet2
On Error Resume Next 'If Word is already running
Set WordApp = GetObject("Word.Application")
If Err.Number <> 0 Then
'Launch a new instance of Word
Err.Clear
'On Error GoTo Error_Handler
Set WordApp = CreateObject("Word.Application")
End If ' Work Running Check
WordApp.Visible = True 'Make the application visible to the user
Set WordDoc = WordApp.Documents.Open(Filename:=DocLoc, ReadOnly:=False) 'Open Template
'This is not workin, no error throw however
'*****************************************
WordDoc.Content.WholeStory
WordDoc.Content.Copy
'***************************************
For component = 15 To 150
iRow = component
If .Cells(iRow, 1).Value = 0 And .Cells(iRow, 2).Text <> "" Then
For CustCol = 3 To 85 'Move Through Columns
If Left(.Cells(13, CustCol).Text, 1) = "[" And Right(.Cells(13, CustCol).Text, 1) = "]" Then
varName = .Cells(13, CustCol).Value 'Determine Variable Name
'varName = "[" & varName & "]"
VarValue = Trim(.Cells(iRow, CustCol).Text) 'Determine Variable Value
With WordDoc.Content.Find
.Text = varName
.Replacement.Text = Application.WorksheetFunction.Text(VarValue, "General")
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll 'Find & Replace all instances
End With
End If
Next CustCol
End If
Next component
'This is not working, no error throw however
'**************************************************************************
WordDoc.Content.MoveDown Unit:=wdParagraph, Count:=2
WordDoc.Content.PasteAndFormat (wdFormatOriginalFormatting)
'**************************************************************************
Filename = Application.ActiveWorkbook.Path & "\ComponentsTable.pdf" 'Create full filename & Path with current workbook location, Last Name & First Name
On Error Resume Next
Kill (Filename) 'Delete filename with the same name if it exists
On Error GoTo 0
On Error Resume Next
WordDoc.ExportAsFixedFormat OutputFileName:=Filename, ExportFormat:=wdExportFormatPDF
WordDoc.Close False
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End With
End Sub
You need to change the logic of your approach.
'WordDoc.Content.WholeStory' specifies an object. Your code does nothing with it. WordDoc.Content.Copy copies an unrelated, other object. Perhaps you mean 'WordDoc.Content.WholeStory.Copy' but this argument is moot. Imagine the entire Word document as one string containing text as well as formatting characters. Therefore you can't copy the WholeStory which is a range. You can only copy its Text.
Once you assign the Text to a string you can paste it to a single cell in Excel. In other words, the String created in Word is understood by Excel and handled within Excel the way Excel handles its own strings. However, that string will definitely contain many characters Excel can't interpret and may contain some that Excel interprets differently. They may even cause Excel to split the original string into more than one cell.
Therefore you need to parse the string lifted from Word and manipulate it into the format you want it to have in Excel. The transition you are asking about takes place at the point where a Word-string becomes an Excel-string. Bear in mind that a Word-range can't become an Excel-range because the two are entirely different animals.
Ok, I found something interesting.
I was not getting any error message because of the
ON ERROR RESUME NEXT
I found that to avoid this, ON ERROR GOTO 0 worked. After that, it was easy to google for errors and find what was wrong. Also, my logic was flawed, I fix it like this. The *Asterix is the interesting part.
Reference https://learn.microsoft.com/en-us/office/vba/api/word.range.copy
Sub GenerateDoc()
Dim WordApp As New Word.Application
Dim WordDoc As Word.Document
DocLoc = Application.ActiveWorkbook.Path & "\CategoryTable2.docx"
'Open Word Template
With Sheet2
On Error Resume Next 'If Word is already running
Set WordApp = GetObject("Word.Application")
If Err.Number <> 0 Then
'Launch a new instance of Word
Err.Clear
'On Error GoTo Error_Handler
Set WordApp = CreateObject("Word.Application")
End If ' Work Running Check
WordApp.Visible = True 'Make the application visible to the user
Set WordDoc = WordApp.Documents.Open(Filename:=DocLoc, ReadOnly:=False) 'Open Template
On Error GoTo 0
'**********************************************************
WordDoc.Range(WordDoc.Content.Start, WordDoc.Content.End).Cut
'
' WordDoc.Content.Selection.WholeStory
' WordDoc.Content.Selection.Copy
For component = 15 To 150
iRow = component
If .Cells(iRow, 1).Value = 0 And .Cells(iRow, 2).Text <> "" Then
'Now past a template copy
'*****************************************************************************************
Set myRange = WordDoc.Range(Start:=WordDoc.Content.End - 1, End:=WordDoc.Content.End - 1)
myRange.Paste
For CustCol = 3 To 85 'Move Through Columns
If Left(.Cells(13, CustCol).Text, 1) = "[" And Right(.Cells(13, CustCol).Text, 1) = "]" Then
varName = .Cells(13, CustCol).Value 'Determine Variable Name
'varName = "[" & varName & "]"
VarValue = Trim(.Cells(iRow, CustCol).Text) 'Determine Variable Value
With WordDoc.Content.Find
.Text = varName
.Replacement.Text = Application.WorksheetFunction.Text(VarValue, "General")
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll 'Find & Replace all instances
End With
End If
Next CustCol
End If
Next component
' WordDoc.MoveDown Unit:=wdParagraph, Count:=2
' WordDoc.PasteAndFormat (wdFormatOriginalFormatting)
Filename = Application.ActiveWorkbook.Path & "\ComponentsTable.pdf" 'Create full filename & Path with current workbook location, Last Name & First Name
On Error Resume Next
Kill (Filename) 'Delete filename with the same name if it exists
On Error GoTo 0
On Error Resume Next
WordDoc.ExportAsFixedFormat OutputFileName:=Filename, ExportFormat:=wdExportFormatPDF
WordDoc.Close False
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End With
End Sub
I am trying to write some VBA code in excel to automate my task of building 100+ .pdf word documents, each following the set template. I originally copied a code from a youtube tutorial showing how to build automated emails from a spreadsheet, and I felt my application was similar enough.
I can get the text replacements to occur as they should. My primary issue is getting images inserted where they need to be. I've attempted using a bookmark and replace code with no luck. I think my issue lies in my variables not having the correct value between the various subs, although that is only my uneducated best guess.
My next issue is creating a code to pull text from an existing document and paste into a new document. I'll be honest, I have been so stuck on the image issue that I haven't even looked into this yet.
I may be going about this task in an inefficient way, however, if someone may be able to spot the fault in my code, it would be greatly appreciated. I have pasted my existing code below. Hopefully it isn't too bad.
Option Explicit
Dim CustRow, CustCol, LastRow, TemplRow, j As Long
Dim DocLoc, TagName, TagValue, TemplName, FileName As String
Dim CurDt, LastAppDt As Date
Dim WordDoc, WordApp As Object
Dim WordContent As Word.Range
Sub CreateWordDocuments()
With Sheet1
If .Range("B3").Value = Empty Then
MsgBox "Please select a correct template from the drop down list"
.Range("G3").Select
Exit Sub
End If
TemplRow = .Range("B3").Value 'Set Template Row
TemplName = .Range("G3").Value 'Set Template Name
DocLoc = Sheet2.Range("F" & TemplRow).Value 'Word Document Filename
'Open Word Template
On Error Resume Next 'If Word is already running
Set WordApp = GetObject("Word.Application")
If Err.Number <> 0 Then
'Launch a new instance of Word
Err.Clear
'On Error GoTo Error_Handler
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True 'Make the application visible to the user
End If
LastRow = .Range("E9999").End(xlUp).Row 'Determine Last Row in Table
For CustRow = 8 To LastRow
Set WordDoc = WordApp.Documents.Open(FileName:=DocLoc, ReadOnly:=False) 'Open Template
For CustCol = 5 To 10 'Move Through 6 Columns
TagName = .Cells(7, CustCol).Value 'Tag Name
TagValue = .Cells(CustRow, CustCol).Value 'Tag Value
With WordDoc.Content.Find
.Text = TagName
.Replacement.Text = TagValue
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll 'Find & Replace all instances
End With
Next CustCol
Call InsertScreenshots
If .Range("I3").Value = "PDF" Then
FileName = ThisWorkbook.Path & "\" & .Range("E" & CustRow).Value & "_" & .Range("G" & CustRow).Value & ".pdf" 'Create full filename & Path with current workbook location, Category_Model
WordDoc.ExportAsFixedFormat OutputFileName:=FileName, ExportFormat:=wdExportFormatPDF
WordDoc.Close False
Else: 'If Word
FileName = ThisWorkbook.Path & "\" & .Range("E" & CustRow).Value & "_" & .Range("G" & CustRow).Value & ".docx"
WordDoc.SaveAs FileName
End If
.Range("O" & CustRow).Value = TemplName 'Template Name
.Range("P" & CustRow).Value = Now
Next CustRow
End With
End Sub
Sub FillABookmark(bookmarkname As String, imagepath As String)
Dim objWord As Object
Dim objDoc As Object
With Sheet1
On Error Resume Next
Set objWord = GetObject(, "Word.Application")
If objWord Is Nothing Then
Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "DocLoc"
End If
Set objDoc = objWord.ActiveDocument
With objDoc
.Bookmarks(bookmarkname).Select
.Shapes.AddPicture FileName:=imagepath
End With
End With
End Sub
Sub InsertScreenshots()
With Sheet1
For CustCol = 11 To 14 'Move Through 4 Columns
TagName = .Cells(7, CustCol).Value 'Tag Name
TagValue = .Cells(CustRow, CustCol).Value 'Tag Value
Call FillABookmark("TagName", "TagValue")
Next CustCol
End With
End Sub
There is a lot going on here and a lot of issues.
Key Points
Learn the value of proper indenting
Dim all variables, otherwise they will be Variants
Early Binding is easier to debug. Use explicit types rather than Object
Don't use Module scoped Variables unless you have a good reason
CodeNames can be useful, but give them meaningful names
Correct test for Empty is IsEmpty
GetObject ClassID is the 2nd parameter. I needed to use Word.Application.16, your installation may vary
Reset your error handling after using On Error Resume Next as soon as you can (this likely was hiding errors from you)
When using EndUp to find the last used row, search from the bottom of the sheet
Simplified the calling of your InsertScreenshots code
You already had a Word app and open doc, don't open it again
Simplified the Insert of image, avoid use of Select
Note: without a sample of your workbook and word doc I can't be sure there aren't other issues, you will need to continue the debug.
See inline comments on changes marked with ~~
Refactored code
Option Explicit
Sub CreateWordDocuments()
'~~ Don't use module scoped variables
'~~ declare all variable types, else they are Variants
Dim CustRow As Long, CustCol As Long, LastRow As Long, TemplRow As Long, j As Long
Dim DocLoc As String, TagName As String, TagValue As String, TemplName As String, FileName As String
Dim CurDt As Date, LastAppDt As Date
'~~ to make debugging easier, use Early Binding (add reference to Microsoft Word), to get Intellisence help. If you need late binding, change back later
Dim WordDoc As Word.Document, WordApp As Word.Application ' Object
Dim WordContent As Word.Range '~~ this suggests you are already using Early Binding!
With Sheet1 '~~ If you are going to use CodeNames, give the sheet a meaningful name (edit it in the Properties window)
If IsEmpty(.Range("B3").Value) Then '~~ correct test for Empty
MsgBox "Please select a correct template from the drop down list"
.Range("G3").Select '~~ will only work if Sheet1 is active
Exit Sub
End If
TemplRow = .Range("B3").Value 'Set Template Row
TemplName = .Range("G3").Value 'Set Template Name
DocLoc = Sheet2.Range("F" & TemplRow).Value 'Word Document Filename
'Open Word Template
On Error Resume Next 'If Word is already running
Set WordApp = GetObject(, "Word.Application.16") '~~ correct format for Office365 - YMMV
If Err.Number <> 0 Then
Err.Clear
On Error GoTo 0 '~~ reset error handling
'Launch a new instance of Word
Set WordApp = New Word.Application ' CreateObject("Word.Application")
WordApp.Visible = True 'Make the application visible to the user
End If
On Error GoTo 0 '~~ reset error handling
WordApp.Visible = True
LastRow = .Cells(.Rows.Count, 5).End(xlUp).Row '~~ use real last row 'Determine Last Row in Table
For CustRow = 8 To LastRow
Set WordDoc = WordApp.Documents.Open(FileName:=DocLoc, ReadOnly:=False) 'Open Template
For CustCol = 5 To 10 'Move Through 6 Columns
TagName = .Cells(7, CustCol).Value 'Tag Name
TagValue = .Cells(CustRow, CustCol).Value 'Tag Value
With WordDoc.Content.Find
.Text = TagName
.Replacement.Text = TagValue
.Wrap = wdFindContinue
.Execute Replace:=wdReplaceAll 'Find & Replace all instances
End With
Next CustCol
For CustCol = 11 To 14 'Move Through 4 Columns ~~ do it here, it's cleaner and easier to reference the Row
TagName = .Cells(7, CustCol).Value '~~ Bookmark Name
TagValue = .Cells(CustRow, CustCol).Value '~~ Image path and name
FillABookmark TagName, TagValue, WordDoc '~~ call to insert each image
Next
If .Range("I3").Value = "PDF" Then
FileName = ThisWorkbook.Path & "\" & .Range("E" & CustRow).Value & "_" & .Range("G" & CustRow).Value & ".pdf" 'Create full filename & Path with current workbook location, Category_Model
WordDoc.ExportAsFixedFormat OutputFileName:=FileName, ExportFormat:=wdExportFormatPDF
WordDoc.Close False
Else '~~ don't need the :
FileName = ThisWorkbook.Path & "\" & .Range("E" & CustRow).Value & "_" & .Range("G" & CustRow).Value & ".docx"
WordDoc.SaveAs FileName
End If
.Range("O" & CustRow).Value = TemplName 'Template Name
.Range("P" & CustRow).Value = Now
Next CustRow
End With
End Sub
Sub FillABookmark(bookmarkname As String, imagepath As String, objDoc As Word.Document)
'~~ Use passed Parameter for Doc
'~~ Don't need select
objDoc.Bookmarks(bookmarkname).Range _
.InlineShapes.AddPicture FileName:=imagepath
End Sub
Context: Every day we get lots of emails containing backup reports and we currently manually count through them and work out what is missing.
I have found a great bit of code (that runs using Visual Basic for Applications) that will pull the emails out of Outlook and put them in Excel.
Now I just need to get rid of the successful ones so it leaves the emails that in the subject line don't have "Result: OK."
Public Sub CopyMailtoExcel()
Dim objOL As Outlook.Application
Dim objFolder As Outlook.Folder
Dim objItems As Outlook.Items
Dim olItem As Object ' MailItem
Dim strDisplayName, strAttCount, strBody, strDeleted As String
Dim strReceived As Date
Dim rCount As Long
' On Error GoTo Err_Execute
Application.ScreenUpdating = False
'Find the next empty line of the worksheet
rCount = Range("A" & Rows.Count).End(-4162).Row
rCount = rCount + 1
Set objOL = Outlook.Application
' copy mail to excel
Set objFolder = objOL.ActiveExplorer.CurrentFolder
Set objItems = objFolder.Items
For Each olItem In objItems
strAttCount = ""
strBody = ""
If olItem.Attachments.Count > 0 Then strAttCount = "Yes"
'On Error Resume Next
'collect the fields
strBody = olItem.Body
' Remove this block if you don't want to remove the hyperlinked urls
Dim Reg1 As RegExp
Dim Match, Matches
Set Reg1 = New RegExp
' remove hyperlinks from bodies for easier reading.
With Reg1
.Pattern = "<[src|http|mailto](.*)>(\s)*"
.Global = True
.IgnoreCase = True
.MultiLine = True
End With
If Reg1.Test(strBody) Then
strBody = Reg1.Replace(strBody, "")
End If
' end remove hyperlinks block
strBody = Trim(strBody)
strReceived = olItem.ReceivedTime
strSender = olItem.SenderName
' column / field
' A Date
' B Time
' C Attachments (Yes)
' D Subject
' E Body
' F From (display name)
' G To (display name)
' H CC (display name)
' I BCC (sent items only)
'write them in the excel sheet
Range("A" & rCount) = strReceived ' format using short date
Range("B" & rCount) = strReceived 'format using time
Range("C" & rCount) = strAttCount
Range("D" & rCount) = olItem.Subject
Range("E" & rCount) = strBody
Range("F" & rCount) = strSender
Range("G" & rCount) = olItem.To
Range("H" & rCount) = olItem.CC
Range("I" & rCount) = olItem.BCC
'Next row
rCount = rCount + 1
Next
' Basic Formatting
Columns("A:I").Select
With Selection
.WrapText = True
.HorizontalAlignment = xlGeneral
.VerticalAlignment = xlTop
.Columns.AutoFit
End With
Columns("E:E").Select ' body column
With Selection
.ColumnWidth = 150
.Rows.AutoFit
End With
Range("A1:I1").Select
With Selection
.VerticalAlignment = xlBottom
.WrapText = False
.RowHeight = 55
End With
' Date and Time
Columns("A:A").Select
Selection.NumberFormat = "[$-409]ddd mm/dd/yy;#"
Range("B:B").Select
Selection.NumberFormat = "[$-F400]h:mm AM/PM"
Range("D:D").Select
Selection.ColumnWidth = 20
Range("A2").Select
Application.ScreenUpdating = True
Set olItem = Nothing
Set objFolder = Nothing
Set objOL = Nothing
Set Reg1 = Nothing
MsgBox "Email import complete"
Exit Sub
Err_Execute:
MsgBox "An error occurred."
End Sub
Below is an example of a successful and a non working backup report email subject line. The profile name is different for each job so that will change.
Success:
ViceVersa Notification. Profile: R4Data_D - Result: OK.
Failure
ViceVersa Notification. Profile: ST29 Data - Result: Source folder not found.
The failed ones won't always be as above as they fail for different reasons so I was thinking that I need an IF or IF NOT Statement of some sort that does something like this:
IF the subject line contains anything other than "Result: OK." then don't export
But I know it would need to allow for different Profile names etc.
The other option is to read out of the body of the email and in that case I would want the macro to only extract emails that don't have "Exit Code: 0" in the body of the email.
Sorry I have no idea about how to construct this!
Credit to original Original Code Diane Poremsky
You should be able to use the following test:
If InStr(olItem.Subject, "Result: OK") = 0
I'm trying to develop a simple code which combines multiple small docx(or rtf) into one docx.
document creation should be based on the following:
1. I have in column A a list of names of the small docs
2. in Column B is one of 2 entries (yes/no)
ex:
A B
doc1 yes
doc2 no
doc3 yes
doc4 yes
doc5 no
3. I have already supplied the location of the small docs in a cell in the sheet
4. also supplied the place where the new (merged) doc would be placed
below is a sample of the code
Application.ScreenUpdating = False
strRandom = Replace(Replace(Replace(Now, ":", ""), "/", ""), " ", "")
MergeFileName = "Merger" & strRandom & ".doc"
MergeFolder = mainworkbook.Sheets("Main").Range("L10").Value
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
Set objSelection = objWord.Selection
'objSelection.TypeText ("Saving this file after this text")
objDoc.SaveAs (MergeFolder & MergeFileName)
For i = 1 To NoOfFiles
If Range("B" & i).Value = "Yes" Then
Set objTempWord = CreateObject("Word.Application")
Set tempDoc = objWord.Documents.Open(Folderpath & "\" & Range("A" & i).Value)
'Set wb = Documents.Open(MyPath & "\" & MyName)
Set objTempSelection = objTempWord.Selection
'objTempSelection.WholeStory
'Selection.Copy
tempDoc.Range.Select
tempDoc.Range.Copy
'Windows(1).Activate
'Selection.EndKey Unit:=wdLine
'objSelection.TypeParagraph
objSelection.PasteSpecial xlPasteAll
.InsertBreak wdPageBreak
tempDoc.Close
End If
Next
objDoc.Save
Application.ScreenUpdating = True
mainworkbook.Sheets("Main").Activate
MsgBox "Completed...Merge File is saved at " & MergeFolder & MergeFileName
FetchFileClicked = False
End Sub
the problem with this code is that it never kills the temp doc opened, so I have 10 docs to be merged I'll end up with 10 WINWORD process and no MSWord windows.
is there a way to fix that problem.
I have heard that if I convert all small docs to .rtf I can parse the file without the need to open it.
I am pulling this code from a userform I use to populate documents from a collection of templates, so my apologies if this doesn't work exactly as I will describe:
Sub Insert_File_From_Location()
CreateObject (Word.Application.Documents.Add)
If ComboBox1.Value = "blah" Then
Selection.InsertFile FileName:="C:\blah.docx"
Else:
End If
End Sub
I took out all of the else if statements to make it look simpler.
A possibility is, taking the above code and manipulating to let your Column B cells define the ComboBox1.Value (yes/no entries). You then would have the Selection.InsertFile FileName:= direct to the location defined in the adjacent cell in Column A. This would need to be a dynamic reference utilizing a loop through the last row.
What I don't have going on is auto-saving the merged document because I have to, typically, manipulate the contents and remove sections that are standard for some templates in my collection.
Hopefully that helps, Karim! When working with just Word docs (.doc or .docx) I do have processes show up in my task manager, but they go away when the insert is completed, leaving me with one Word process for the opened document.
After some serious troubleshooting I finally got it to work, and here the code below.
Application.ScreenUpdating = False
strRandom = Replace(Replace(Replace(Now, ":", ""), "/", ""), " ", "")
MergeFileName = "Merger" & strRandom & ".doc"
MergeFolder = mainworkbook.Sheets("Main").Range("L10").Value
Set objWord = CreateObject("Word.Application")
Set appWord = GetObject(, "Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
Set objSelection = objWord.Selection
objDoc.SaveAs (MergeFolder & MergeFileName)
For i = 1 To NoOfFiles
If Range("B" & i).Value = "Yes" Then
myName = (Folderpath & "\" & Range("A" & i).Value)
With appWord.Selection
.InsertFile Filename:=myName
End With
With objWord.Selection
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=7
End With
End If
Next
objDoc.Save
Application.ScreenUpdating = True
mainworkbook.Sheets("Main").Activate
MsgBox "Completed...Merge File is saved at " & MergeFolder & MergeFileName
PS: thanks Cyril for the tip it was the key to resolve that pain of mine
Let’s try something like combining multiple Word documents; you need to copy all the contents of each one, and paste everything into one consolidated Word doc. That could take a very long time, especially if there are many files in the folder. Simply run the script below and the code will do all the work for you.
Sub MergeAllWordDocs1()
Dim i As Long
Dim MyName As String, MyPath As String
Application.ScreenUpdating = False
Documents.Add
MyPath = "C:\Users\your_path_here\" ' <= change this as necessary
MyName = Dir$(MyPath & "*.do*") ' not *.* if you just want doc files
Do While MyName <> ""
If InStr(MyName, "~") = 0 Then
Selection.InsertFile _
FileName:="""" & MyPath & MyName & """",
ConfirmConversions:=False, Link:=False,
Attachment:=False
Selection.InsertBreak Type:=wdPageBreak
End If
MyName = Dir() ' gets the next doc file in the directory
Loop
End Sub