VBA: Reading excel data into word - vba

I am making a simple form that extract the data from my excel sheet, such as name, date of birth, and address. And inserting them into my word form, I am doing 20-30 sheets everytime, so I think it might be able to save the copying & pasting time.
I tried to follow this tutorial: http://www.makeuseof.com/tag/integrate-excel-data-word-document/
And created a button with a simple label named m_name, for member's name. But it tells me Compile error: User-defined type not defined. And flaged on line 1.
I am using Word 2003, (I am not able to find the Tools > Reference as the guide was asking for). I am not sure if it is related to this error.
Private Sub CommandButton1_Click()
Dim objExcel As Excel.Application
Dim exWb As Excel.Workbook
Set exWb = objExcel.Workbooks.Open("U:\test.xls")
ThisDocument.m_name.Caption = exWb.Sheets("Member's Data").Cells(3, 3)
exWb.Close
Set exWb = Nothing
End Sub

Yes, it's very important to set references according to the tutorial.
However, change these two lines:
Dim objExcel As Excel.Application
Dim exWb As Excel.Workbook
to:
Dim objExcel As Object
Set objExcel = CreateObject("Excel.Application")
and the code should work, too.

Related

Manipulate a word document ("caller"/"context") from an excel workbook ("callee"/"controller") that was opened by it

Background
I have a Word-macro in Normal.dotm that opens an Excel-workbook Reference Check.xlsm.
The macro uses RegExp as well as Range.Find to find strings of a certain pattern, and then it places this information onto sheets in the Excel-workbook.
This is the basic template:
Sub GetReferencesAndHyperlinksToExcel()
' Shortcut Key: Ctrl+[Num *]
Dim oRegex As New RegExp
Dim oRegExMatches As MatchCollection
Dim oRegExMatch As Match
Const strPattern As String = "(my pattern)"
Dim SourceDocument As Document
Dim oStory As Range
Dim hl As Hyperlink
Dim xlApp As New Excel.Application
Dim xlWorkbook As Excel.Workbook
Dim R as Excel.Range
' Set the context
Set SourceDocument = ActiveDocument
' Load the spreadsheet
Set xlWorkbook = xlApp.Workbooks.Open("C:\...\Reference Check.xlsm")
' Set starting range to write to
With xlWorkbook.Worksheets("Reference Checks")
.Range("ref").ClearContents
Set R = .Range("ref")(1, 1)
End With
' Initialise regex
With oRegex
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
' ==== Iterate through story ranges, then execute regex and write matches and hyperlinks to the spreadsheet ====
' ==== Iterate through story ranges, then iterate through hyperlinks and write hyperlinks to the spreadsheet ====
End Sub
The Excel-workbook does some calculations and lookups (with pre-filled column formulas) against a Data Table within the Workbook.
Using that information, I manipulate the active Word document (the "caller" or the "context") in predictable^ ways.
^If it's predictable, then we should be able to use a macro to do the work for us.
The problem
I want to use the now-open Excel workbook Reference Checks.xlsm as a "console" or "controller", where I can change some data, and use data, to perform operations on (make changes to) the document.
To do this, I believe I need to somehow be able to refer to the original "caller" or "context", i.e. the Word document that was Active when I originally called it (Set SourceDocument = ActiveDocument), from within the now-open Workbook. This means that either:
Macros within Excel (tied to Buttons) Reference Check.xlsx act on SourceDocument (preferred), or
Macros within Excel (tied to Buttons) Reference Check.xlsx call a Macro within Word Normal.dotm and then act on the SourceDocument* (if this is possible, the above should be), or
Various macros within Normal.dotm act on SourceDocument* (workable, but clunky)
*Note: This must actually be SourceDocument (the "caller" or "context") and not ActiveDocument, because it is possible that as I switch between windows, another document could become ActiveDocument.
Things I've thought of
For option 1, use a global variable in Reference Checks.xlsm, then when I load the workbook, set the reference to SourceDocument. This is my preferred option. I have no idea how to do this, however.
For option 3, use a global variable in Normal.dotm, set the reference to the workbook when I open it, then read information in the workbook when I call the macros. A drawback would be that I have many macros I might call, and I would have to have many public subs (makes Normal.dotm quite unwieldy).
Help
How do I do this?
I have tested this and it worked perfectly with Office 2010.
Note that you need the Excel Library in your Word Normal Template and the Word Library in the Excel Reference Check.xlsm
You will need the following:
Sub in the ThisWorkBook module in the Reference Check.xlsm.
So in your Excel VBA Project -> Microsoft Excel Objects -> ThisWorkBook
Option Explicit
Sub ExcelWordController(WordDocFromWord As Document)
'If you are wanting to use it as a Document then _
you will need the Word Library in Excel
MsgBox WordDocFromWord
'Just put some funny text inthe doc for a test
WordDocFromWord.Range(0, 0).Text = "Yeah Baby It works"
'Here you can then call someother Sub or so some processing
End Sub
Then in your Word Normal project:
Option Explicit
'Sub in Word Normal
Sub ExcelControlWordFromWordInitiation()
'Obvisouly you alrady have the Excel Library in the Word Doc
Dim xlApp As New Excel.Application
'xlWorkbook is a object in the Word Excel Library
'So I changed the name
Dim RefCheckWorkBook As Excel.Workbook
Dim R As Excel.Range
Dim SourceDocument As Document
Set SourceDocument = ActiveDocument
'You want to be able to see the Excel Application
xlApp.Visible = True
Set RefCheckWorkBook = xlApp.Workbooks.Open(Environ("USERPROFILE") & "\Desktop\Reference Check.xlsm")
'Calling the Sub in Excel from Word
Excel.Application.Run "ThisWorkBook.ExcelWordController", SourceDocument
End Sub

Powerpoint VBA to switch back to powerpoint from Excel

I hope someone can help....
I have a powerpoint presentation, which has linked tables and graphs from an excel file. the updating of the slides are set to manual.
i have created a VBA code in Powerpoint which opens up the excel file. I am trying to update the links in the powerpoint through VBA instead of manually choosing each linked element and updating the values. while the first part of my VBA code works in opening up the excel file, the links are not being updated, which i think is down to not being back in the powerpoint to update the links, so I am trying to include in my VBA code lines which will go back to the powerpoint presentation, after which i assume the the line to update links will work (happy to be corrected). below is the code i have built so far....my comments are in bold ...
any suggestions?
FYI, I am using office 2007.
Thanks
Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("File location\filename.xlsm", True, False)
Set xlApp = Nothing
Set xlWorkBook = Nothing
Section above opens the excel file which contains the linked tables and charts
On Error Resume Next
With GetObject(, "PowerPoint.Application")
.ActivePresentation.SlideShowWindow.Activate
End With
Section above i was hoping would go back to the powerpoint after opening the excel file but it does not which is why i think the code below to update links is not working
ActivePresentation.UpdateLinks
End Sub
Start from something easier. This will allow you to activate the first existing PowerPoint application from Excel:
Option Explicit
Public Sub TestMe()
Dim ppt As New PowerPoint.Application
ppt.visible = msoTrue
ppt.Windows(1).Activate
End Sub
Then play a bit with it and fix it into your code.
#Vityata
Ok, i got it to work....original coding did the first part of opening the excel file, and to switch back to powerpoint (and i think this will only work if there is only 1 presentation open i added the following code...
AppActivate "Microsoft PowerPoint"
so my complete code looks like:
Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("file path\file name.xlsm", True, False)
Set xlApp = Nothing
Set xlWorkBook = Nothing
AppActivate "Microsoft PowerPoint"
End Sub
now to get manual links to update as part of the vba code...
If you capture the file that your macro is in. This is just a string of your path and filename
'This is the macro file
MacroFile = ActivePresentation.FullName
Then you can use that variable to activate just that specific PowerPoint presentation.
Use Presentations(MacroFile).Activate
or Presentations(MacroFile).Updatelinks
It's best not to use ActivePresentation when moving between applications.

Error Closing OLEObject Excel.Sheet After Creation

Say you wish to create and then close a linked excel sheet:
Dim shp As shape
Set shp = Application.ActiveDocument.Shapes.AddOLEObject(ClassType:="Excel.Sheet")
DoEvents
shp.OLEFormat.Object.Close
This fails with this error:
Run time error '1004'
Close method of Workbook class failed
Why? I can't seem to find any examples of this occurring in word, the closest example I can find is this, which is more related with the user form than the actual function.
The error seems very generic, is there any way to get a more specific reason "why" the close method is failing? It seems if you google around, you'll find this error is thrown for all sorts of reasons(example, another example) but non of these seem to have anything to add to this particular issue.
Note: A similar error occurs with "shp.OLEFormat.Object.Save"
The usual reason for this question is to get the object to "unselect" on the document surface...
In my experience, it's not possible to close a workbook activated on the document surface. This has to do with how OLE Embedding works. Application.Quit should work, but doesn't (in my experience) with Excel.
The most reliable way to achieve this has been to force the workbook to open in an independent Excel.Application window, then you can close and save the workbook and Quit the Excel application.
Something like the following should work:
Dim shp as Word.Shape
Dim oleF as Word.OLEFormat
Dim xlBook as Excel.Workbook 'or Object
Dim xlApp as Excel.Application 'or Object
Set shp = Application.ActiveDocument.Shapes.AddOLEObject(ClassType:="Excel.Sheet")
Set olef = shp.OLEFormat
oelf.DoVerb VerbIndex:=wdOLEVerbOpen
Set xlBook = olef.Object
Set xlApp = xlBook.Application
'Do things here
xlBook.Close
xlApp.Quit
Set xlApp = Nothing
Set xlBook = Nothing
Note that for debugging purposes you might want to set xlApp.Visible = True.
It can happen that xlBook.Close still generates an error, even though the behavior other than that is correct. In that case the error can be surpressed by turning off error messages for this one line, re-instating it following:
On Error Resume Next
xlBook.Close
On Error GoTo 0
Here's what I came up with:
Set xlBook = olef.Object
Set xlApp = xlBook.Application
xlApp.SendKeys "{ESC}"
This will stop the Excel.Application and return the user to Word. Same thing as running the commanding to close the Workbook.

AutoNew macro not working

I'm trying to get Word to open an Excel document whenever a document based on a specific template is created.
Here is my macro
Sub AutoNew()
Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open("E:\Letters.xlsx")
End Sub
When I double-click the template, it brings up a document based on the template just fine, but the macro doesn't run.
It shows up in the list of macros in the template, but attempting to run it doesn't do anything.
As has mentioned KazJaw, make app visible
Sub AutoNew()
Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open("E:\Letters.xlsx")
oExcel.Visible = true
End Sub
A disadvantage is, that excel application is launching as a new task (see tak manager) in case of another calling the macro - every document is opened in its own task.
The correct way is use API for launching a document in registered application, for example here: http://access.mvps.org/access/api/api0018.htm
Or one-row workaround, ugly, but works great:
Shell "cmd.exe /c start D:\a\test.xlsx"
Note that template with macro must have extension .xltm, not .xltx.

Open Excel file in VBA from Powerpoint

I'm trying to open the Excel file using VBA in Powerpoint 2010 with the help of following code.
Private Sub CommandButton1_Click()
Dim xlApp As Excel.Application
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
xlApp.Workbooks.Open "C:\lol\Book1.xlsx", True, False
Set xlApp = Nothing
Range("A8").Value = "Hello"
End
But I'm getting the following error.
Compile Error
User Defined type not defined.
Am I missing something. Can anyone share the sample piece of code to open an excel file, change a cell value and close Excel file in Powerpoint 2007 and 2010 using VBA.
I have searched a lot and tried different pieces of code, but getting the same error everytime. :(
Thanks in advance. :)
Have you added a reference to the Excel Object Model? That would save you having to use the late bound objects (and you get the benefit of having the Intellisense help when you are coding).
You need to go to Tools -> References and check the "Microsoft Excel v.x Object Library" (I think that number changes depending on the version of office you are using.
Your code should work if you do that, you should also remove the
CreateObject("Excel.Application")
line and replace it with
Set xlApp = new Excel.Application
And move the
Set xlApp = nothing
line to the end of your subroutine.
The rest of your code looks fine to me.
Late binding code would be this
Private Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkbook = xlApp.Workbooks.Open("C:\lol\Book1.xlsx", True, False)
xlWorkbook.sheets(1).Range("A8").Value = "Hello"
Set xlApp = Nothing
Set xlWorkbook = Nothing
End Sub
It's better to use early binding though.