Export data from excel to word using VBA - vba

I want to export data from a spreadsheet such as name, date of birth, address etc to a letter that I'm writing in word.
I've been following this tutorial:
I've had success in populating the information in word using a command button, but i don't want the ugly grey button in word so i tried making a macro and pasted the same script into a macro vba.
here is the script I'm using when trying to make the macro:
Sub Macro1()
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
Set exWb = objExcel.Workbooks.Open("C:\Users\Admin\Desktop\Case Log.xlsx")
ThisDocument.solicitor.Caption = exWb.Sheets("Sheet1").Cells(4, 3)
exWb.Close
Set exWb = Nothing
End Sub
when i run the macro it highlights the word "solicitor" and displays the message "Compile error: Method or data member not found"
I've checked and rechecked and the label name is correct, it works with the command button, i don't understand why it shouldn't work as a macro.
Any helps would be much appreciated.

I found a native solution for doing this.
Mail Merge!
I set one up and saved it, now everytime I open the document, it loads all the info from the spreadsheet which it is already pointing to.
Thanks for all the suggestions

Related

Word VBA Runtime Error 5460 on second Documents.Add in global template

For a customer, I have created a Global template with a ’New Document” button that shows a userform letting the user create a new document from a choice of templates, e.g. Letter, Invoice, etc.
Recently, we have added the choice Report.
The code executed from this userform is very simple, using e.g.
Documents.Add Template:="Letter.dotm", NewTemplate:=False
to create the new documents.
The Report template is – by my standards – quite complex, with AutoNew and AutoClose macros, an EventClassModule, it writes to and reads from the CustomDocumentProperties, opens several specific Word documents from where it copies text and pastes it into the Report document, etc.
The first time a new Report is created it works as planned; but the second time (in the same Word session) the Report option is used, a ‘Runtime Error 5460’ occurs. And after that, any of the other document options returns the same error.
Quitting Word and starting a new Word session sets everything back to normal, until the Report template again is called the second time.
Strangely enough, the Report template works with no errors when new documents based on it are created directly from Explorer, as many times in the same Word session as needed.
The problem occurs in Word 2016 (365) with Windows 7 Pro, but not in Word 2013 with Windows 10.
Anybody that has ever experienced anything like this?? Help is really appreciated.
Runtime Error 5460: 'A file error has occured.'
Debug is not possible.
The Report template has thousands of lines of code and I have not been able to find out if it is in fact code in the Report template that causes the error, or code in the Global template.
As said, the Report template works fine when used from Explorer, and when called via the Global template in 2013 everything works there too.
Problem solved!
I followed the advice from #macropod and added the path also.
In stead of just using
'…
If OptionButton3.Value = True Then
Documents.Add Template:="Report.dot", NewTemplate:=False
End If
'…
I changed the code to:
Private Sub CommandButton1_Click()
Dim strPath As String
strPath = Options.DefaultFilePath(wdWorkgroupTemplatesPath)
Dim wdApp As Word.Application
Set wdApp = GetObject(, "Word.Application")
'…
If OptionButton3.Value = True Then
wdApp.Documents.Add Template:=strPath & "\Report.dot", NewTemplate:=False
End If
'…
End Sub
Thanks!!

Outlook VBA insert URL not working

I can insert manually a picture into an outlook 2010 new email using "Insert picture" and the “insert link to file” feature. In the File field I enter the link: http://www.example.com/image.php?s1=song1.net & c1=composer
The link returns an image and I can see it in the body of the email.
I need to enter this URL using VBA. I wrote the code below and it does not work. When I tried to run it came with the following message: Run-time error ‘4198’: Command failed. It highlights the line that includes the link.
My code:
Sub insertHTMLFile()
Dim Insp As Inspector
Set Insp = ActiveInspector
If Insp.IsWordMail Then
Dim wordDoc As Word.Document
Set wordDoc = Insp.WordEditor
wordDoc.Application.Selection.InsertFile "http://www.example.com/image.php?s1=song1.net & c1=composer ", , False, False, False
End If
End Sub
I would appreciate it if you can show me how I can use VBA to insert the image as I did it manually. Unfortunately Outlook does not have a macro recorder which could show me the instructions how to do it.
Try to use %20 to replace/encode spaces in the URL string.
Also I'd suggest recording a VBA macro in Word to see the exact line of code required to get the job done using the Word object model. Word provides the Macro recorder which allows to do the job manually and get the code generated for you in the background. See Record or run a macro for more information.
The following script worked fine for me in Outlook:
Set wordDoc = Application.ActiveInspector.WordEditor
wordDoc.Application.Selection.InlineShapes.AddPicture "http://www.dimastr.com/redemption_logo.png", true, false

Access VBA: SUB designed to refresh an Excel Spreadsheet giving an error

Relative VBA newbie here. I created a new Module "QCDataRefresh" with a Public Sub "RefreshExcel" that is designed to open an Excel spreadsheet (housed on my network drive) in the background and refresh it. This is done in order to refresh the many data links contained within said spreadsheet.
Here is the code for this Sub:
Public Sub RefreshExcel()
Dim appExcel As Object
Set appExcel = CreateObject("Excel.Application")
appExcel.workbooks.Open ("\\renssfile2\shares\Supply Chain Project Management\QCData.xlsx")
appExcel.activeworkbook.refreshall
Set appExcel = Nothing
End Function
Running this gives a run-time error '1004': "Application Defined or object-defined error. Debugging seems to highlight the line of code "appExcel.activeworkbook.refreshall". Not sure why though?
Additionally, I am also attempting to create a button in Access to run this from my dashboard. To do this, I created a new button, and created a new Event Procedure for this entitled, "Command101_Click".
The following is the code for that Event, which attempts to run my RefreshExcel Sub upon clicking the button:
Private Sub Command101_Click()
QCDataRefresh.RefreshExcel
End Sub
When I run this Event, I would expect it to give me the same error from my refresh Function above. However, instead it opens a window asking me to select a Macro. I'm unsure what my mistake is here, but I'm sure that it must be a simple oversight. Thoughts on this as well?
Thanks all!
I think the problem is that the workbooks.open method returns a workbook.
Try this:
Public Sub RefreshExcel()
Dim appExcel As Object
Dim excelwb As Excel.Workbook
Set appExcel = CreateObject("Excel.Application")
Set excelwb = appExcel.workbooks.Open ("\\renssfile2\shares\Supply Chain Project Management\QCData.xlsx")
excelwb.refreshall
Set excelwb = Nothing
Set appExcel = Nothing
End Sub
Whenever I have unexpected and unusual issue\error for using excel to output to or read from I allways try the following, especially when the code breaks in the middle and doesn't get to the line where you close the spreadsheet and close the Excel object from memory.
So close your spreadsheet and any Excel instances and objects you may have as follow:
Close all Excel files and excel program if you have any open
Go to the Task Manager (by doing Alt+Ctrl+Del) then select Task Manager
Go to processes tab
Sort by process name
Look for any Excel.exe in the list and force close them all one by one
Let us know.

VBS file to refresh external data in specific work sheets

I want to create a .VBS file to refresh a table on a spcific worksheet. This table's data comes from an external data source (MS query). Usually, I just right click on the table and go to Refresh. This is what I would like to duplicate in the .VBS file. Is this possible?
I researched this on Stackoverflow (and Google), but I wasn't having luck finding code for the specific worksheet, just for the workbook. I'd like to do this for the specific sheet.
I did research how to access an Excel worksheet through .VBS, and this is what I have so far:
Dim objXLApp, objXLWb, objXLWs
Set objXLApp = CreateObject("Excel.Application")
Set objXLWb = objXLApp.Workbooks.Open("C:\Test\Test.xlsx")
Set objXLWs = objXLWb.Sheets(6)
' This is the code I added to solve my problem
For Each qry In objXLWs.QueryTables
qry.Refresh(false)
Next
objXLWs.Calculate
' End
objXLWb.Save
objXLWb.Close (False)
Set objXLWs = Nothing
Set objXLWb = Nothing
objXLApp.Quit
Set objXLApp = Nothing
MsgBox "Done"
Now, "objXLWs.Refresh" doesn't work. Neither does RefreshAll, RefreshAllData, etc. I get "Object does not support this property or method." I also tried .Calculate, but it doesn't work for this case. I am wondering if there is something that I am missing, or if I have to restructure this code a different way?
Any guidance would be appreciated.
Thanks,
Mark
Try something like
objXLWb.Connections("YourConnectionName").Refresh

Update linked fields in Word document from Excel VBA

I am trying to automatically update certain information (such as names, dates and numbers) across 3 different Word documents by putting the data into a spreadsheet and linking to the respective cells from Word. The spreadsheet has some Macros in it which auto-update parts of the spreadsheet internally.
Everything is working fine, except for updating the links in the Word documents.
When trying to update a link in Word by right-clicking on it and selecting the "update link" option it brings up the Macro warning dialog for the spreadsheet, asking whether I want to activate Macros or not. It doesn't do this just once but constantly during the 20s or so the update process takes (which seems unusually long to me). So updating the link works, but only if you're willing to click the "activate Macros" button of a few dozen times.
I tried to automate updating all fields in a document from Word with VBA, but that has the same problem, it also brings up the Macros dialog constantly for half a minute.
Here's my code for that:
Sub UpdateFields()
ActiveDocument.Fields.Update
End Sub
I also tried to update the Word documents directly from the spreadsheet, but that does not work either, because when Excel tries to open a Word document via VBA the program stops executing and trows this error:
"Excel is waiting for another application to complete an OLE action."
Clicking ok and waiting does not help because the error message reappears after a few seconds, and the only way to stop it is to manually kill the Excel process.
Here's my Excel Macro code:
Sub LoopThroughFiles()
Path = Application.ActiveWorkbook.Path
Dim WordFile As String
WordFile = Dir(Path & "\*.doc")
Do While Len(WordFile) > 0
Run Update(Path & "\" & WordFile)
WordFile = Dir
Loop
End Sub
Function Update(Filepath As String)
Dim WordDoc As Word.Document
Set WordApplication = CreateObject("Word.Application")
Set WordDoc = WordApplication.Documents.Open(Filepath) 'This produces the error
ActiveDocument.Fields.Update
End Function
Note that the only files in the folder are the 3 documents and the spreadsheet, and the program does find the files without any problems.
I have searched for solutions online but I did not really find anything, which I found odd, since it seems like a pretty common thing that someone would do with VBA.
Then again, I have very little experience with VBA, so I might be completely missing the point and there is a super simple solution I am just not aware of.
I think I see the error, which is a silent failure, becuase the document contains links, there is an open dialog waiting for you to say "yes" or "no" to update the links.
We can suppress this dialog by disabling the automatic link updates (WordApplication.Options.UpdateLinksAtOpen = False).
Function Update(Filepath As String)
Dim WordApplication As Word.Application
Dim WordDoc As Word.Document
Dim updateLinks As Boolean
Set WordApplication = CreateObject("Word.Application")
updateLinks = WordApplication.Options.UpdateLinksAtOpen 'capture the original value
WordApplication.Options.UpdateLinksAtOpen = False 'temporarily disable
Set WordDoc = WordApplication.Documents.Open(Filepath)
WordDoc.Fields.Update
'MsgBox "Links updated in " & WordDoc.Name
'## Save and Close the Document
WordDoc.Save
WordDoc.Close
'## reset the previous value and Quit the Word Application
WordApplication.Options.UpdateLinksAtOpen = updateLinks '
WordApplication.Quit
End Function
Also, remember to Save and Close the document, and Quit the word application inside the function.
I made this other modification:
In your function, ActiveDocument is not an object in Excel, so you would need to qualify it, otherwise that line will also throw an error. Rather than refer to WordApplication.ActiveDocument, I just simply refer to the WordDoc which you have already assigned.