VBA_Newbie123
New Member
- Joined
- May 20, 2017
- Messages
- 9
Hi,
I am having a bit of trouble getting this code to work. I have broken it down simply to have a single text box in the word document 'Word.docx' and have named it "Test" using the 'plain text content control' I have clicked the design mode all on the developer tab in word and then changed the name to "Test" and saved the document.
Next I have created a new macro enabled excel spreadsheet and ticked the word box in tools -> reference in the VBA display. In the excel sheet only two cells have values, E8 contains "Hello" and F8 contains "Saved"
When I run the script it should open the word document, enter "Hello" into the saved text box, rename it "Saved" then save as in both a word doc and pdf.
Below is the script i'm trying to run;
I am having a bit of trouble getting this code to work. I have broken it down simply to have a single text box in the word document 'Word.docx' and have named it "Test" using the 'plain text content control' I have clicked the design mode all on the developer tab in word and then changed the name to "Test" and saved the document.
Next I have created a new macro enabled excel spreadsheet and ticked the word box in tools -> reference in the VBA display. In the excel sheet only two cells have values, E8 contains "Hello" and F8 contains "Saved"
When I run the script it should open the word document, enter "Hello" into the saved text box, rename it "Saved" then save as in both a word doc and pdf.
Below is the script i'm trying to run;
Code:
Sub populatesub()'declare variables
Dim wdApp As Object, wdDoc As Object
Dim strdocname As String
Dim fName As String, fPath As String
Dim ws As Worksheet
'set values
Set ws = ThisWorkbook.Sheets("Sheet1")
fPath = "C:\sample sheet testing\"
fName = ws.Range("F8").Value
strdocname = "Word.docx"
'Word environment
Set wdApp = CreateObject("Word.Application")
wdApp.Visible = True
wdApp.Activate
On Error Resume Next
Set wdDoc = wdApp.Documents.Open(fPath & strdocname)
If Err.Number > 0 Then Exit Sub
wdDoc.Activate
'update text box
wdDoc.Shapes("Test").TextFrame.TextRange.Text = ThisWorkbook.Sheets("Sheet1").Range("E8").Value
'save the files
wdDoc.SaveAs Filename:=fPath & fName
wdDoc.SaveAs2 fPath & fName & "pdf", 17
wdApp.Quit
Set wdDoc = Nothing
Set wdApp = Nothing
Application.CutCopyMode = False
End Sub