Word remains in the background despite the "Active" function VBA - excel

I need to make barcode label sheets for items. For this I use Excel with VBA and a "user form" to help the user in entering the number and information of bar codes. Once I have all my information for my barcodes, I transfer its information to a Word in which I format it to make printable labels.
My system works fine, although a bit long when there are a large number of labels to transfer, but once word and excel have been closed once when I want to restart the transfers, Word no longer comes to the fore , which makes me completely miss the transfer. I am using the tab key which is the main source of the problem.
I have tried performing the same actions as the tab key with other commands like "next" so that it is no longer a problem. However this does not work entirely because the tab key allows at the end of a page to continue the layouts on a new page which the "next" function does not do.
So my questions are: How can I force Word to come to the fore? Can we replace the tab key with another parameter that allows me to do the same thing?
I provide you below the code of my loop performing the transfer.
Dim appwd As Word.Application
Dim oDoc As Object
Dim Code As String, SKU As String, Name As String, Size As String
Dim DerLign As Byte
With Sheets("Reference")
DerLign = .Cells(.Cells.Rows.Count, 1).End(xlUp).Row
End With
On Error Resume Next
Set appwd = GetObject(, "Word.Application")
If Err Then
Set appwd = New Word.Application
End If
On Error GoTo 0
With appwd
If .Documents.Count = 0 Then
.Documents.Add
End If
Set oDoc = .MailingLabel.CreateNewDocument("3474")
.Visible = True
.Activate
' Colle les données dans Word
For i = 8 To DerLign
Code = ThisWorkbook.Worksheets("Reference").Range("B" & i)
SKU = ThisWorkbook.Worksheets("Reference").Range("C" & i)
Name = ThisWorkbook.Worksheets("Reference").Range("D" & i)
Size = ThisWorkbook.Worksheets("Reference").Range("E" & i)
appwd.Selection.ParagraphFormat.Alignment = 1
appwd.Selection.TypeParagraph
appwd.Selection.TypeText Text:=SKU
appwd.Selection.TypeParagraph
appwd.Selection.Font.Name = "Code EAN13"
appwd.Selection.Font.Size = 40
appwd.Selection.TypeText Text:=Code
appwd.Selection.Font.Name = "Calibri"
appwd.Selection.Font.Size = 11
appwd.Selection.TypeParagraph
appwd.Selection.TypeText Text:=Name + " " + Size
SendKeys "{TAB}", False
Next i
End With
End Sub
Regards

Related

Word to Excel data transfer of bookmark section locations (cross references)

I am trying to obtain the numbered locations of my bookmarks (paragraph number without context) in a Word document (a lengthy legal document template) and. I am currently using the following code to pull the bookmarked text values from the Word document into an Excel workbook I've built out to grab other data from other sources, but I haven't been able to figure out how to manipulate the code to grab the bookmark's paragraph numbers (I searched high and low for this one too, and am a VBA newbie. I know just enough to be dangerous, but not enough to be helpful lol). Please Help!
Sub SectionLocationImportTESTING()
Dim intDocCount As Integer
Dim wdApp As Word.Application, wdDoc As Word.Document, xlWb As Excel.Workbook, xlWs As Excel.Worksheet
Dim BookmarkText As String
Set wdApp = GetObject(, "Word.Application")
On Error GoTo 0
If wdApp Is Nothing Then
MsgBox "There are no MS Word Documents open.", vbInformation, "No Word Documents open"
Exit Sub
End If
Set xlWb = ThisWorkbook
Set xlWs = ActiveWorkbook.Sheets("Data Input")
intDocCount = wdApp.Documents.Count
If intDocCount > 1 Then
MsgBox "There are " & intDocCount & " Word Documents open." & vbNewLine & vbNewLine & _
"Please close the additional MS Word Documents", vbCritical, "Too many Word Documents open!"
Set wdApp = Nothing
Exit Sub
End If
With wdApp
Set wdDoc = wdApp.ActiveDocument
wdDoc.Activate
'This is very abbreviated, I have about 300 bookmarks that transfer
If wdDoc.Bookmarks.Exists("Section_Rent") = True Then
BookmarkText = wdDoc.Bookmarks("Section_Rent").Range.Text
xlWs.Cells(202, 22) = ("Section_Rent")
xlWs.Cells(202, 23) = BookmarkText
End If
End With
ActiveWorkbook.RefreshAll
ActiveSheet.PivotTables("Data_Input_Table").PivotFields("Trimmed Data"). _
PivotFilters.Add2 Type:=xlCaptionIsGreaterThan, Value1:="0"
Columns("D:D").EntireColumn.AutoFit
Range("A1").Select
MsgBox "Transfer is complete."
End Sub
I don't think there's a straight-forward way of doing that.
You could do this for example:
Sub Tester()
Debug.Print ParagraphNumber(Selection.Range)
End Sub
Function ParagraphNumber(rng As Range)
ParagraphNumber = rng.Document.Range(0, rng.End).Paragraphs.Count
End Function
...but it will also count "empty" paragraphs.
If you have a lot of bookmarks, you could consider listing the names in your Excel sheet and then looping over that range to run the text extraction. If you hard-code all those names into your VBA that's going to be very hard to maintain.
E.g.
'...
Dim c As Range, bm As String, rngBM As Word.Range
'...
'...
Set wdDoc = wdApp.ActiveDocument
wdDoc.Activate
'range with your bookmark names
Set rngBM = ThisWorkbook.Sheets("Bookmarks").Range("A2:A300")
For Each c In rngBM.Cells
bm = c.Value 'bookmark name
If wdDoc.Bookmarks.Exists(bm) Then
Set rngBM = wdDoc.Bookmarks(bm).Range
'for demo purposes just putting info next to the bookmark name...
c.Offset(0, 1).Value = rngBM.Text
c.Offset(0, 2).Value = ParagraphNumber(rngBM)
End If
Next c
There's 2 ways to get the paragraph number, depending on what you want:
Option 1
This will get the exact string of the auto-numbering that you see in the paragraph itself:
E.g. the below paragraph will get you 1.
This is a test paragraph.
If wdDoc.Bookmarks.Exists("Section_Rent") Then
Dim BookmarkText As String
BookmarkText = wdDoc.Bookmarks("Section_Rent").Range.Text
xlWs.Cells(202, 22) = "Section_Rent"
xlWs.Cells(202, 23) = BookmarkText
Dim BookmarkParaNum As String
BookmarkParaNum = wdDoc.Bookmarks("Section_Rent").Range.ListFormat.ListString
xlWs.Cells(202, 24) = BookmarkParaNum
End If
Option 2
This will get the string that you see if you insert a cross reference to the paragraph:
Using the below code for the same paragraph in Option 1 will give you just 1, the same as what inserting it as cross reference will get you.
wdDoc.Paragraphs.Last.Range.InsertParagraphAfter 'A temporary paragraph for inserting field later
Dim fieldRng As Range
Set fieldRng = wdDoc.Paragraphs.Last.Range.Duplicate
If wdDoc.Bookmarks.Exists("Section_Rent") Then
Dim BookmarkText As String
BookmarkText = wdDoc.Bookmarks("Section_Rent").Range.Text
xlWs.Cells(202, 22) = "Section_Rent"
xlWs.Cells(202, 23) = BookmarkText
fieldRng.InsertCrossReference ReferenceType:="Bookmark", ReferenceKind:=wdNumberNoContext, ReferenceItem:="Section_Term", InsertAsHyperlink:=True, IncludePosition:=False, SeparateNumbers:=False, SeparatorString:=" "
Dim tempField As Field
Set tempField = fieldRng.Fields(1)
Dim BookmarkParaNum As String
BookmarkParaNum = tempField.Result
xlWs.Cells(202, 24) = BookmarkParaNum
tempField.Delete
End If
fieldRng.Delete 'Delete the temporary paragraph

Creating a multilevel list in Outlook from Excel VBA

I am working with excel to process user input and then output an standardized email based on the input, and then take that formatted text and save it to a variable to later add it to the clipboard for ease of entry into a system we use for internal documentation.
I have a functioning approach using HTML for the email format, but that doesn't resolve my intent to have it copy the code to the clipboard or variable as the HTML tags are copied as well. I'm hoping to get the functionality of Word's bullet lists so I've been trying to adapt the MS Word code in a way that can be called on demand.
I currently have the default excel libraries, form library and object library for Word and Outlook added to the program.
My goal is to pass an array list built on excel tables through the Word list and have it format and write the text to Word editor in an outlook draft. There will be varying number of sections (No more than 6) needed to be written, typically no more than 10 items per section, usually less. So I intend to have other sub/functions call this to format each section as needed.
Attached is an example of output for this section, along with an example of where the data is coming from. Each section will have it's own sheet in Excel. The second level of the list for each section will come from a separate sheet.
I included a portion of the actual code showing the startup of a new outlook draft and entry of text. EmailBody() currently just handles any text outside of these sections, and calls a separate function for each section to parse the tables (currently as unformatted text, and only inputting line breaks).
Output Example
Data source example
Sub Email()
Dim eTo As String
eTo = Range("H4").Value
Dim myItem As Object
Dim myInspector As Outlook.Inspector
Dim wdDoc As Word.Document
Dim wdRange As Word.Range
Set myItem = Outlook.Application.CreateItem(olMailItem)
With myItem
.To = eTo
.Bcc = "email"
.Subject = CNum("pt 1") & " | " & CNum("pt 2")
'displays message prior to send to ensure no errors in email. Autosend is possible, but not recommended.
.Display
Set myInspector = .GetInspector
'Obtain the Word.Document for the Inspector
Set wdDoc = myInspector.WordEditor
If Not (wdDoc Is Nothing) Then
Set wdRange = wdDoc.Range(0, wdDoc.Characters.Count)
wdRange.InsertAfter (EmailBody(CNum("pt 1"), CNum("pt 2")))
End If
'[...]
end with
end sub
Multilevel list code I am struggling to adapt. I keep getting an error on the commented out section of code, and unsure of how to properly correct it so that it both functions and can be called on demand:
Run-time error '450': Wrong number of arguments or invalid property
assignment
Sub testList()
Dim arr1 As Object
Set arr1 = CreateObject("System.Collections.ArrayList")
With arr1
.Add "test" & " $100"
.Add "apple"
.Add "four"
End With
Dim i As Long
With ListGalleries(wdBulletGallery).ListTemplates(1).ListLevels(1)
.NumberFormat = ChrW(61623)
.TrailingCharacter = wdTrailingTab
.NumberStyle = wdListNumberStyleBullet
.NumberPosition = InchesToPoints(0.25)
.Alignment = wdListLevelAlignLeft
.TextPosition = InchesToPoints(0.5)
.TabPosition = wdUndefined
.ResetOnHigher = 0
.StartAt = 1
.LinkedStyle = ""
End With
ListGalleries(wdBulletGallery).ListTemplates(1).Name = ""
'Selection.Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
' ListGalleries(wdBulletGallery).ListTemplates(1), ContinuePreviousList:= _
' False, ApplyTo:=wdListApplyToWholeList, DefaultListBehavior:= _
' wdWord10ListBehavior
'writes each item in ArrayList to document
For i = 0 To arr1.Count - 1
Selection.TypeText Text:=arr1(i)
Selection.TypeParagraph
Next i
'writes each item to level 2 list
Selection.Range.SetListLevel Level:=2
For i = 0 To arr1.Count - 1
Selection.TypeText Text:=arr1(i)
Selection.TypeParagraph
Next i
Selection.Range.ListFormat.RemoveNumbers NumberType:=wdNumberParagraph
arr1.Clear
End Sub
Please forgive me if any of this seems inefficient, or an odd approach. I literally pickup up VBA a few weeks ago and only have a few hours of application in between my job responsibilities with what I've learned so far. Any assistance would be much appreciated.
The reason why you are getting that error is because, it is not able to resolve the object Selection. You need to fully qualify the Selection object else Excel will refer to the current selection from Excel.
You may have referenced the Word Object library from Excel but that is not enough. The simplest way to reproduce this error is by running this from Excel
Sub Sample()
Selection.Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
ListGalleries(wdBulletGallery).ListTemplates(1), ContinuePreviousList:= _
False, ApplyTo:=wdListApplyToWholeList, DefaultListBehavior:= _
wdWord10ListBehavior
End Sub
Here is a sample code which will work. To test this, open a word document and select some text and then run this code from Excel
Sub Sample()
Dim wrd As Object
Set wrd = GetObject(, "word.application")
wrd.Selection.Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
ListGalleries(wdBulletGallery).ListTemplates(1), ContinuePreviousList:= _
False, ApplyTo:=wdListApplyToWholeList, DefaultListBehavior:= wdWord10ListBehavior
End Sub
Applying this to your code. You need to work with the Word objects and fully qualify your objects like Word Application, Word Document, Word Range etc. For example
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
FlName = "C:\MyFile.Docx"
'~~> Establish an Word application object
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.Application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
Set oWordDoc = oWordApp.Documents.Open(FlName)
With oWordDoc
'
'~~> Rest of the code here
'
End With
Utilizing Word lists, while functional in this circumstance created a certain tedium in coding due to the need to declare both Word and Outlook objects and resolve their relation to each other.
It appears I was declaring my HTML lists incorrectly in my original code. I shifted the margin of the <li> rather than nesting <ul> to step the list.
By nesting the HTML list tags you can get the same functionality of a word list and the formatting will persist when copied to other text editors. However, copying must be done after it is written to .HTMLBody.
<ul><li>Apple</li><ul><li>Fruit</li></ul></ul>
or for VBA:
.HTMLBody = "<ul><li>" & arg1 & "</li><ul><li>" & arg2 & "</li></ul></ul>"
The above will output this to .HTMLBody:
AppleFruit
To copy the text you only need to select all the text in the Outlook word editor and then assign it to the clipboard if pasting as is, or assign it to a variable if additional changes are needed before putting it in the clipboard.

Finding heading of chapters in word file and copying individual paragraphs to new word file with VBA

Since nobody was able to help me with the problem I posted here before (link is below), I am now trying to solve the task through VBA.
Finding a heading in word file and copying entire paragraph thereafter to new word file with python
To briefly recap, I have a large amount of word files, which I would like to reduce to a more readable size each. In each file, there is one heading that appears several times, always formated as a 'Heading 2'. I look for this specific heading which occurs several times in a document and I want to copy all the text parts in just these chapters with the respective heading to a new word document.
I decided to create an excel file in which I list the files and the respective heading of the chapters that I want to copy (see picture below).
To do this now I have written the following code:
Sub SelectData()
Application.ScreenUpdating = False
Dim WdApp As Word.Application
Set WdApp = CreateObject("Word.Application")
Dim Doc As Word.Document
Dim NewDoc As Word.Document
Dim HeadingToFind As String
Dim ChapterToFind As String
Dim StartRange As Long
Dim EndRange As Long
Dim WkSht As Worksheet
Dim LRow As Long
Dim i As Long
Set WkSht = ThisWorkbook.Sheets("Sheet1")
LRow = WkSht.UsedRange.Cells.SpecialCells(xlCellTypeLastCell).Row
With WkSht
For i = 1 To LRow
If Dir(.Cells(i, 1).Text, vbNormal) = "" Then
.Cells(i, 3).Value = "Please check File Location"
Else
Set Doc = WdApp.Documents.Open(Filename:=.Cells(i, 1).Text, _
AddToRecentFiles:=False, Visible:=False, ReadOnly:=False)
Set NewDoc = Documents.Add
ChapterToFind = LCase(.Cells(i, 2).Text)
With Doc
Selection.HomeKey Unit:=wdStory
With Selection
With .Find
.ClearFormatting
.Text = ChapterToFind
.MatchWildcards = False
.MatchCase = True
.Execute
End With
If .Find.Found Then
.Collapse wdCollapseStart
With .Find
.Text = ""
.Style = "Heading 2"
.Forward = False
.Execute
End With
.MoveDown Count:=1
.HomeKey Unit:=wdLine
StartRange = .Start
.Find.Forward = True
.Find.Execute
.Collapse wdCollapseStart
.MoveUp Count:=1
.EndKey Unit:=wdLine
EndRange = .End
Doc.Range(StartRange, EndRange).Copy
NewDoc.Content.Paste
NewDoc.SaveAs2 Doc.Path & "Clean" & ".docx", wdFormatFlatXML
Else
WkSht.Cells(i, 4).Value = "Error Chapter Not Found"
End If
End With
End With
WdApp.Quit
Set Doc = Nothing: Set NewDoc = Nothing: Set WdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
End If
Next
End With
End Sub
However I am really struggling. It seems to not work as I constantly get an error with the command (RunTimeError 438):
Selection.HomeKey Unit:=wdStory
I am aware that I have to activate the Microsoft Word 15.0 Object Library in the references to be able to get word commands. Nevertheless it is not working.
I would greatly appreciate any help, I am also open to other suggestions of course.
The word files look something like in the picture below, however the chapter that I want to extract can occur several times within one word document. As a result my code would probably need a loop or something, I was not able to get this done.
Also I have considered the following links to the topic:
Use VBA with Powerpoint to Search titles in a Word Doc and Copy Text into another Word Document
VBA: open word from excel
word vba: select text between headings
Did I understand this correctly? The following code is the core of what I think you're trying to do. It finds the first Heading 2, then finds all the paragraphs after it until it finds another header of any type or the end of the document. startCopyRange and endCopyRange is the range of those paragraphs. You'll have to piece this into your Excel routine.
A few notes. Always save the active document to a variable and work from that; the user is then free to change active documents while this routine is running. Never use Selection, always use ranges. Never use relative movements like Move, always use API calls.
Sub SelectData()
Dim Doc As Word.Document
Set Doc = ActiveDocument
Dim findRange As Range
Set findRange = Doc.Range
ChapterToFind = "My Chapter"
findRange.Find.Text = ChapterToFind
findRange.Find.Style = "Heading 2"
findRange.Find.MatchCase = True
Dim startCopyRange As Long
Dim endCopyRange As Long
Do While findRange.Find.Execute() = True
startCopyRange = findRange.End + 1
endCopyRange = -1
'findRange.Select
Dim myParagraph As Paragraph
Set myParagraph = findRange.Paragraphs(1).Next
Do While Not myParagraph Is Nothing
myParagraph.Range.Select 'Debug only
If InStr(myParagraph.Style, "Heading") > 0 Then
endCopyRange = myParagraph.Range.Start - 0
End If
If myParagraph.Next Is Nothing Then
endCopyRange = myParagraph.Range.End - 0
End If
If endCopyRange <> -1 Then
Doc.Range(startCopyRange, endCopyRange).Select 'Debug only
DoEvents
Exit Do
End If
Set myParagraph = myParagraph.Next
DoEvents
Loop
Loop
End Sub

Printing multiple document types with different page settings

I have an automation script running whose output is various document types and printing those documents with various printer settings. I am printing to the same printer for all documents, so that's nice. I have three excel worksheets that need to be printed. These I am printing using the built-in "PrintOutEx" method. One onto a letter size paper and two to 11x17. Next, I have the script print a word document, which I am printing using the built-in "PrintOut" method. This is to be printed on an 11x17 paper but scaled so that two pages print side by side. Lastly, I have to print a multi-page tiff document which I am printing using a print handler. I am having a number of issues with this and I apologize if these are silly question and appreciate any help I can gather.
I am trying to keep the default printer the same as when I start the subroutines and that doesn't seem to be working using the PrinterSettings methods.
About the default printer: the default printer changes to the printer I want (doesn't change back at the end). The default printer is set to 11x17. If I change the default settings of the printer to 8.5x11 everything prints to 8.5x11.
The script seems to be ignoring the settings/pagesettings/setups that I am providing it with.
The word document print is not scaled to fit the paper and I have tried setting the paper size to 11x17 as well as 8.5x11 and scaling the print but that just looks really bad.
The first excel worksheet does not print to a letter size paper.
The second and third worksheets work okay (as long as the default printer settings are as desired; see point 2).
The multipage tiff document prints okay as long as the default printer's default settings are correct.
I am not a professional programmer so I apologize if the question has a simple answer or the code looks horrifying. I researched tons on this question and couldn't find a solution that worked. :( I stepped through the code line by line and there are no errors. I am attaching the code I have thus far.
Thanks!!!
Public Sub PrintSPIDPackage(SPID As String)
On Error GoTo errHandler
Dim printerSettings As New Printing.PrinterSettings
Dim curPrinter As String
Dim engPrinter As String
Dim purPrinter As String
engPrinter = "engBLAH"
purPrinter = "purBLAH"
curPrinter = printerSettings.PrinterName
Dim spidBBPath As String
spidBBPath = ****REDACTED
spidDrawingPackagePath = ***REDACTED***
Dim eAPP As New Excel.Application
Dim wB As Excel.Workbook
Dim wS As Excel.Worksheet
Dim rng As Excel.Range
Dim lRow As Integer
Dim wAPP As New Word.Application
Dim doc As Word.Document
wB = eAPP.Workbooks.Open(spidBBPath)
wS = wB.Worksheets(selectedSheet & " OPs")
wS.PageSetup.PaperSize = Excel.XlPaperSize.xlPaperLetter 'I would think this causes the printer to printout to a letter size paper
wS.PrintOutEx(ActivePrinter:=engPrinter)
wS = wB.Worksheets(selectedSheet)
lRow = wS.Range("A" & wS.Rows.Count).End(Excel.XlDirection.xlUp).Row + 3
rng = wS.Range("A1:I" & lRow)
rng.PrintOutEx(ActivePrinter:=engPrinter) 'PRINT SHOULD BE AN 11x17
wS = wB.Worksheets(selectedSheet & " MLB")
wS.PrintOutEx(ActivePrinter:=engPrinter) 'PRINT SHOULD BE AN 11x17
wB.Close(False)
eAPP.Quit()
Runtime.InteropServices.Marshal.ReleaseComObject(wS)
Runtime.InteropServices.Marshal.ReleaseComObject(wB)
Runtime.InteropServices.Marshal.ReleaseComObject(eAPP)
If InStr(xPath, ".doc") <> 0 Then
doc = wAPP.Documents.Open(xPath)
wAPP.ActivePrinter = engPrinter
doc.PageSetup.PaperSize = Word.WdPaperSize.wdPaperLetter ''''''print out should be 11x17 with two pages side by side
wAPP.PrintOut(PrintZoomColumn:=2, PrintZoomRow:=1) ', PrintZoomPaperHeight:=2 * (11 * 1440), PrintZoomPaperWidth:=2 * (8.5 * 1440)) '''''AS you see I tried scaling...
doc.Close(False)
doc = Nothing
wAPP.Quit()
wAPP = Nothing
End If
Dim pDoc As New Printing.PrintDocument
currPage = 0
AddHandler pDoc.PrintPage, AddressOf pDocPage
PrintDialog1.Document = pDoc
pDoc.DefaultPageSettings.Landscape = True
pDoc.DocumentName = SPID & "-Drawing Package"
pDoc.PrinterSettings.PrinterName = engPrinter
pDoc.DefaultPageSettings.Landscape = True
pDoc.DefaultPageSettings.Margins.Left = 50
pDoc.DefaultPageSettings.Margins.Right = 50
pDoc.DefaultPageSettings.Margins.Top = 50
pDoc.DefaultPageSettings.Margins.Bottom = 50
Dim ps As New Printing.PaperSize("Tabloid", 1700, 1100)
ps.PaperName = Printing.PaperKind.Tabloid
pDoc.DefaultPageSettings.PaperSize = ps
pDoc.Print()
printerSettings.PrinterName = curPrinter 'this should reset the user's default printer to the original setting to before when this routine started??
Exit Sub
errHandler:
MsgBox(Err.Description)
End Sub
Sub pDocPage(ByVal sender As Object, ByVal e As Printing.PrintPageEventArgs)
Dim img As Image = Image.FromFile(spidDrawingPackagePath)
Dim pCount = img.GetFrameCount(FrameDimension.Page)
img.SelectActiveFrame(FrameDimension.Page, currPage)
Using stReader As IO.MemoryStream = New IO.MemoryStream
img.Save(stReader, ImageFormat.Bmp)
Dim bmp As Bitmap = CType(Image.FromStream(stReader), Bitmap)
e.Graphics.DrawImage(bmp, 0, 0)
bmp.Dispose()
End Using
currPage += 1
If currPage < pCount Then
e.HasMorePages = True
End If
End Sub

How do I open a word document via VBA macro in read write more and write Text into the Document?

I am getting the Message
Open Read only
Local Copy
Recieve Notification when available
I need to open the doc in the read write mode, and the document is closed before the macro is executed
Also I ahve doubts on the way I am writing the Text
Sub Read_Write_Document()
Dim p As Long, r As Long
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("C:\Documents and Settings\Desktop\Word_File_read_write_1.docx")
Dim i As Integer
i = 1
With wrdDoc_Read
For p = 1 To .Paragraphs.Count
Set tRange = .Range(Start:=.Paragraphs(p).Range.Start, End:=.Paragraphs(p).Range.End)
tString = tRange.Text
tString = Left(tString, Len(tString) - 1)
If InStr(1, tString, "1") > 0 Then
If Mid(tString, 1, 4) = "date" Then
tRange.Text = "DATE" ' Write Text
End If
End If
Next p
End With
.SaveAs ("C:\Documents and Settings\Desktop\Word_File_read_write_2.docx")
wrdApp.Quit ' close the Word application
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
Couple of things
A
It's always advisable to use Option Explicit
You have declared the word document as wrdDoc but are using wrdDoc_Read
Change the line
With wrdDoc_Read
to
With wrdDoc
B
Next your .SaveAs routine is outside the With - End With and hence will give you error
C
You are directly quitting the word application without closing the word document. It's always good to issue a wrdDoc.Close (False) after a .SaveAs because there are instances where an installed add-in can make changes to your document and quitting the word application will prompt the .SaveAs again.
D
Instead of looping through the cells and replacing the text, you can use .Find and Replace

Resources