Editing Excel spreadsheats from Word with VBA - excel

How do I edit excel spreadsheets from word using VBA?

First you need to set a reference to the version of Excel you are running. In the VBE go to Tools>References and click Microsoft Excel 12.0 Object Library (12.0 for 2007, 11.0 for 2003) etc.
Then you can code something like this (opens a new instance of Excel, opens, edits and saves a new workbook). You'd use GetObject to access a running instance of Excel:
Sub EditExcelFromWord()
Dim appExcel As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Set appExcel = CreateObject("Excel.Application")
With appExcel
.Visible = True
Set wb = .Workbooks.Add
Set ws = wb.Worksheets(1)
ws.Range("A1").Value2 = "Test"
wb.SaveAs ThisDocument.Path & Application.PathSeparator & "temp.xls"
Stop 'admire your work and then click F5 to continue
Set ws = Nothing
Set wb = Nothing
Set appExcel = Nothing
End With
End Sub

Related

Creating an Excel Workbook via PPT VBA

I am able to open .xlsx file by CreateObject("Excel.Application").Workbooks.Open("path")
Something like this is not allowing me to create a new Excel Workbook via a PowerPoint Macro.
Set ExcelFile = CreateObject("Excel.Application")
ExcelFile.Workbooks.Add
ExcelFile.ActiveWorkbook.SaveAs "path"
sample code, just checked on PP 2016:
(remember to close xlsApp, set obj to nothing etc.)
Public Sub StackOverflow()
Dim xlsApp As Object
Dim wkbWorking As Object
Set xlsApp = CreateObject("Excel.Application") 'basically it opens excel application
Set wkbWorking = xlsApp.Workbooks.Add 'it creates new workbook in just opened excel
xlsApp.Visible = True 'makes excel visible
wkbWorking.SaveAs "C:\Temp\PesentationExcel.xlsx"
wkbWorking.Close 'closes workbook
xlsApp.Quit 'closes excel application
'sets variables to nothing
Set wkbWorking = Nothing
Set xlsApp = Nothing
End Sub

Excel Variable Opens Outlook If I try To View It In Locals Window

I am trying to rename a copied worksheet in Excel using word VBA. When I try to set my worksheet variable to the new worksheet it tries to open Microsoft Outlook 2016. With each line after that (stepping through) it opens a dialogue box asking me to create a new Microsoft Outlook account.
The code does successfully create the copies of the template sheet but it fails to rename them.
** Edited to clarify the real issue and to add "Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn) 'Opens Excel" which was already in the workbook macro when the problem occurred.
Dim oXL As Excel.Application 'Requires loading "Microsoft Excel 16.0 Object Library" from Tools -> References
Dim oWB As Excel.Workbook
Dim oSheet As Excel.Worksheet
Set oXL = New Excel.Application
Set oWB = oXL.Workbooks.Open(FileName:=WorkbookToWorkOn) 'Opens Excel
oXL.Visible = True
For i = LBound(seller_names) To UBound(seller_names)
With oXL.ActiveWorkbook
.Sheets("Template").Copy After:=.Sheets(.Sheets.Count)
Set oSheet = Sheets(.Sheets.Count) 'set worksheet to be the template copy
If Len(seller_names(i)) > 31 Then
oSheet.name = Left(seller_names(i), 31)
Else
oSheet.name = seller_names(i)
End If
End With
Next i
The line "Set oSheet = Sheets(.Sheets.Count) is where the open Outlook bug occurs. Both lines oSheet.name = run without generating errors but fail to rename the worksheet.
I fixed this issue by changing
.Sheets("Template").Copy After:=.Sheets(.Sheets.Count)
to
.Sheets("Template").Copy After:=.Sheets("Template (2)")

VBA Using Outlook to open excel not opening

Hi Thanks for your help.
I have the follow code in Outlook 2010 & 2007:
Sub Openexcel()
Dim xlApp As Object
Dim sourceWB As Workbook
Dim sourceSH As Worksheet
Dim strFile As String
Set xlApp = CreateObject("Excel.Application")
With xlApp
.Visible = True
.EnableEvents = False
End With
strFile = "E:\All documents\susan\work\Excel projects\saving files to directory Clean.xls"
Set sourceWB = Workbooks.Open(strFile, , False, , , , , , , True)
Set sourceSH = sourceWB.Worksheets("Sheet2")
sourceWB.Activate
End Sub
This code works the first time I use it after opening outlook but if I then close the excel file I can not use it again. I need to reopen this work book about 3 times
The Question at
Outlook VBA open excel
seen to have the same problem but I did not understand the answer.
"I got it figured out. I was opening a different workbook and then closing it before I try to open the second one and that was interfering with it. To fix this I kept the excel app open and reset the workbook object to the new workbook i wanted"
If some someone could help with the additional code that would be great.
Great code found at Excel interactions don't work after Excel file opened.
why I could not find this last week who knows.
Sub Openexcel()
' change
Dim xlApp As Excel.Application
Dim sourceWB As Excel.Workbook
Dim sourceSH As Excel.Worksheet
'change
Set xlApp = New Excel.Application
With xlApp
.Visible = True
.EnableEvents = False
'.UserControl = False
'.DisplayAlerts = False
'.AskToUpdateLinks = False
End With
strFile = "E:\All documents\susan\work\Excel projects\saving files to directory Clean.xls"
'change
Set sourceWB = xlApp.Workbooks.Open(strFile, , False, , , , , , , True)
Set sourceSH = sourceWB.Worksheets("Sheet2")
sourceWB.Activate
End Sub
Thanks guys for all your thoughts.
You need to declare the Excel Applicaton at the global scope and use it to open another workbooks. Not to create a new Excel instance for opening new files. You may find the How to automate Microsoft Excel from Visual Basic article helpful.
For example, declare the Application object outside the event handler:
Dim oXL As Excel.Application
Private Sub Command1_Click()
Dim oWB As Excel.Workbook
Thus, you will be able to re-use it for closing and opening new workbooks.

Access query to a macro enabled excel template using vba

Im trying to put data from a query which requires a parameter into a excel template with marcos in it however I keep getting errors. Im getting the parameter from the form.
heres my code:
Private Sub exportButton_Click()
Dim XL As Excel.Application
Dim wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset
'Set up refernce to the query to export
Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
'Execute Query
Set rsResults = qdfResults.OpenRecordset()
'reference excel
Set XL = CreateObject("Excel.Application")
'refernce workbook
Set wbTarget = XL.Workbooks.Open("C:\Users\user\Documen…\folder\resultTemplate.xltm")
'clear excel sheet
wbTarget.Worksheets("marktable").Cells.ClearContents
'paste data from query to worksheet
wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults
'save workbook
** 1) 'wbTarget.SaveAs ("C:\Users\user\Documents
\folder\resultTemplate1.xlsm")
** 2) wbTarget.SaveAs FileName:="C:\Users\user\Documents\folder\resultTemplate1.xlsm",
FileFormat:=xlOpenXMLWorkbookMacroEnabled
'clear variables
Set wbTarget = Nothing
Set XL = Nothing
Set qdfResults = Nothing
End Sub
with 1) i could get the data into a work book but without the macros
with 2) i can get the data in and macro but wont save properly
any suggestions?
EDIT**
by wont save properly i mean that it is creating a temperory file that i cannot save
and now it wont even created that, now its creating a file with 0 bytes and no type
cant answer by own question yet but until I can heres my working code:
The only problem I can see was that wbTarget.Close and XL.Quit werent used which caused the module to still run and the file therefore wasn't completely saved but temporary. Credit to #Gord Thompson
Private Sub exportButton_Click()
Dim XL As Excel.Application, wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset
Set XL = New Excel.Application
Set wbTarget = XL.Workbooks.Open("C:\Users\user\Documents\folder\ResultsTemplate.xltm")
Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
Set rsResults = qdfResults.OpenRecordset()
wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults
wbTarget.SaveAs "C:\Users\user\Documents\folder\Results.xlsm", xlOpenXMLWorkbookMacroEnabled
wbTarget.Close
Set wbTarget = Nothing
XL.Quit
End Sub
Strange behaviour in Office automation projects can often be the result of failing to properly Close objects and Quit applications. In this case adding
wbTarget.Close
and
XL.Quit
statements appears to have resolved the issue.
The only problem I can see was that wbTarget.Close and XL.Quit werent used which caused the module to still run and the file therefore wasn't completely saved but temporary. Credit to #Gord Thompson
Private Sub exportButton_Click()
Dim XL As Excel.Application, wbTarget As Workbook
Dim qdfResults As QueryDef
Dim rsResults As Recordset
Set XL = New Excel.Application
Set wbTarget = XL.Workbooks.Open("C:\Users\user\Documents\folder\ResultsTemplate.xltm")
Set qdfResults = CurrentDb.QueryDefs("MarksQuery")
qdfResults.Parameters("Forms!comp!competition") = Forms!comp!competition
Set rsResults = qdfResults.OpenRecordset()
wbTarget.Worksheets("markTable").Cells(1, 1).CopyFromRecordSet rsResults
wbTarget.SaveAs "C:\Users\user\Documents\folder\Results.xlsm", xlOpenXMLWorkbookMacroEnabled
wbTarget.Close
Set wbTarget = Nothing
XL.Quit
End Sub

Excel 2007 ODBC data populates when opened via Windows Explorer, but not when opened via Access VBA

I have an Excel 2007 workbook that contains an ODBC data connection (to FoxPro, if that matters). The connection is set to "refresh data when opening the file."
When I go into File Explorer and open the workbook, the data populates into the spreadsheet as it should. However, when I execute a function in Access VBA that opens the workbook, the data from the ODBC connection does not populate.
Why would it make a difference which way the workbook is opened? And more importantly, how can I get the data to populate when the workbook is opened via Access VBA?
Here is the Access VBA code that opens the workbook:
Public Sub Subform_cmdOpenFile_Click(frm As Form)
Dim rs As Recordset
Dim ftiSuperclass As FilingTemplateInterface
Set rs = frm.RecordsetClone
If (rs.BOF Or rs.EOF) Then GoTo PROC_EXIT
Set ftiSuperclass = New FilingTemplateInterface
ftiSuperclass.ShowWorkbook rs!Directory & frm!Filename
PROC_EXIT:
On Error Resume Next
rs.Close
Set rs = Nothing
ftiSuperclass.QuitExcel
Set ftiSuperclass = Nothing
Exit Sub
PROC_ERROR:
Resume PROC_EXIT
End Sub
Friend Sub ShowWorkbook(strFilename As String)
Dim fso As New Scripting.FileSystemObject
Dim appExcel As New Excel.Application
appExcel.Workbooks.Open Filename:=strFilename, AddToMRU:=True
appExcel.visible = True
Set appExcel = Nothing
End Sub
Resolved by adding the line of code noted below, to force connection refresh on open:
Friend Sub ShowWorkbook(strFilename As String)
Dim fso As New Scripting.FileSystemObject
Dim appExcel As New Excel.Application
appExcel.Workbooks.Open Filename:=strFilename, AddToMRU:=True
appExcel.ActiveWorkbook.Connections("ConnectionName").Refresh 'added this line
appExcel.visible = True
Set appExcel = Nothing
End Sub

Resources