Creating and saving Excel document From VBA in Word - vba

I want to be able to run a macro in a Word document that will create an Excel document and then save that spreadsheet in a shared folder.
This is the code I have so far:
Public Sub Monthly_Commission_Extract()
Dim objExcel
Dim objDoc
Dim objSelection
Dim SaveAs1 As String
SaveAs1 = ("\\stnlinasshd01\P403759\Month End\Monthly Commission Extract\1st Save")
Set objExcel = CreateObject("Excel.Application")
Set objDoc = objExcel.Workbooks.Add
objExcel.Visible = True
Set objSelection = objExcel.Selection
ActiveWorkbook.SaveAs FileName:=SaveAs1, FileFormat:=-4158, CreateBackup:=False
Application.DisplayAlerts = True
End Sub
The code is giving me an error:
Run-time error '424': Object required
At the following piece of code:
ActiveWorkbook.SaveAs FileName:=SaveAs1, FileFormat:=xlText, CreateBackup:=False
Please advise how I get around this.

objExcel.ActiveWorkbook.SaveAs
not just
ActiveWorkbook.SaveAs
Anything which "belongs" to Excel must be prefixed with your objExcel application reference.

Below is a simple and straight forward code that creates a new excel workbook and saves it into a path on your local disk. This VBA code has ben tested from inside MS Word.
Private Sub CreateExcel()
Dim myExcel As Object
Dim myWb As Object
Set myExcel = CreateObject("Excel.Application")
Set myWb = myExcel.Workbooks.Add
Application.DisplayAlerts = False
myWb.SaveAs FileName:="D:\test\dump.xls"
Application.DisplayAlerts = True
myWb.Close False
Set myWb = Nothing
myExcel.Quit
Set myExcel = Nothing
End Sub
In your case, the following would have worked because 'objDoc' is derived from the excel object reference.
objDoc.SaveAs FileName:=SaveAs1, FileFormat:=-4158, CreateBackup:=False

Oh captain, yes my captain,
the errormessage says clearly that a object is missed, I think this line
SaveAs1 = ("\stnlinasshd01\P403759\Month End\Monthly Commission Extract\1st Save")
is the problem You should a SET-Statement out of this, by starting this line with "SET ", then you have the object required.

Related

Window not visible despite running in background

I have a macro that I'm trying to run through Access that will open up an excel sheet, do some actions on it, and then leave the sheet open.
I have most of it working, with the exception of not being able to get my excel document to open visibly. If I check the task manager, an excel process is running in the background so something does happen, just nothing that I can physically see.
I've attempted to sample some code found through stackoverflow and other resources, which I'm sure you'll see some of that in my current code. But I tried for about an hour with no avail.
Private Sub Command1_Click()
Dim fd As FileDialog
Dim MySheetPath As String
Dim Xl As Excel.Application
Dim XlBook As Excel.Workbook
Dim XlSheet As Excel.Worksheet
On Error GoTo ErrorHandler
'allowing selection of the time
Set fd = Application.FileDialog(msoFileDialogFilePicker)
fd.AllowMultiSelect = False
If fd.Show = True Then
If fd.SelectedItems(1) <> vbNullString Then
MySheetPath = fd.SelectedItems(1)
End If
Else
End
End If
Set Xl = CreateObject("Excel.Application")
Set XlBook = GetObject(MySheetPath)
ShowaWindow (MySheetPath)
Set XlSheet = XlBook.Worksheets(1)
XlSheet.Rows(2).EntireRow.Insert
XlSheet.Range("D2") = "ABC"
Set Xl = Nothing
Set XlBook = Nothing
Set XlSheet = Nothing
Exit Sub
ErrorHandler:
Set fd = Nothing
MsgBox "Error " & Err & ": " & Error(Err)
End Sub
Sub ShowaWindow(sFileName As String)
Dim oWb As Workbook
Set oWb = GetObject(sFileName)
For Each oWb In Workbooks
If LCase(oWb.Name) <> LCase(sFileName) Then
oWb.Windows(1).Visible = True
Exit For
End If
Next
End Sub
Ideally I would like to be able to see the worksheet appear.
Set Xl = CreateObject("Excel.Application")
Xl.Visible=True
You don't need to put it immediately after creating the object, just before you set the object to Nothing.
Set XlBook = GetObject(MySheetPath)
This is wrong. Don't use GetObject to open the workbook, use the Excel.Application instance you just created:
Set XlBook = Xl.Workbooks.Open(MySheetPath)
Later you iterate all opened workbooks:
For Each oWb In Workbooks
But that's not the Workbooks collection from the Xl application instance, it's the Workbooks collection from the instance that's currently running your code - you need to qualify it with the Xl object:
Private Sub ShowaWindow(ByVal app As Excel.Application, ByVal sFileName As String)
'...
For Each oWb In app.Workbooks
Also, make the app instance visible after you created it, and don't forget to invoke XlBook.Close and Xl.Quit to properly tear down that EXCEL.EXE process when you're done.

how to save macro code as vbs?

I don't know why I can't call my macro code from R, This is my code that I'm trying to save as vbs file: (should I save it in Notepad application?)
Sub vb()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("path.xlsm", 0, False)
xlApp.Visible = True
xlApp.Run "Countries"
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
How can I save the above code as vbs ?
You can export a code module from the project explorer, right-click on it and select Export File....
You can also do it with VBA, i.e. to export "Module1":
With ThisWorkbook.VBProject.VBComponents("Module1")
.Export "c:\so\" & .Name & ".bas"
End With
Use the below VBS code as you cannot save VBA code as VBS as the schema or say they are not in the same page as C and C++ are different it is in the same way
Set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Open("path.xlsm")
objExcel.Application.Visible = True
objExcel.Application.Run "path.xlsm!Countries" 'Refer to the below if the code is under sheet
objExcel.ActiveWorkbook.Close
WScript.Echo "Finished."
WScript.Quit
If you have placed the code in the sheet. user this line
objExcel.Application.Run "path.xlsm!sheet1.dog"
Hope this resolve your query. Happy Coding.

VBA: Activate method not found

I have some VBA code that was working perfectly a few weeks ago, but now is crashing with an error. The code, which is triggered from Word, is meant to open an Excel file. The specific error I'm getting is related to the Activate method.
Sub Populate()
Dim eApp As Excel.Application
Dim eWB As Excel.Workbook
Dim eSheet As Excel.Worksheet
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set eApp = New Excel.Application
End If
'Open Workbook
WorkbookName = "(Excel file location)"
eApp.Visible = True
eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
eWB.Activate
(etc.)
I'm a VBA novice so I'm sure there's a better way to write the above. It's the final line - eWB.Activate - that creates a compile error, "Method or data member not found." Again, this was working last month and isn't working now. Has something changed in Office 2016 that makes this code illegal?
I played around and think I have a workaround, but I'd still like to know why this is crashing, for future reference. Thanks.
EDIT: Here is the error
Do not know why you have that Error when you have On Error Resume Next from there on. Are there codes missing from what you have posted? Also is the Excel workbook macro enabled that may interfere the codes in Word?
You may also try Late Binding for those Excel Objects once you are done coding with IntelliSense. Just to demonstrate how I would code this Excel file open part (Excel 2010):
Option Explicit
Sub Populate()
Dim eApp As Object ' Excel.Application
Dim eWB As Object ' Excel.Workbook
Dim eSheet As Object ' Excel.Worksheet
Dim ExcelWasNotRunning As Boolean
Dim WorkbookName As String
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If eApp Is Nothing Then Set eApp = CreateObject("Excel.Application")
ExcelWasNotRunning = eApp Is Nothing
If ExcelWasNotRunning Then Exit Sub
'Open Workbook
WorkbookName = "C:\Test\Tables.xlsx"
eApp.Visible = True
'eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
On Error GoTo 0 ' Turns on Debug prompt on Error
If Not eWB Is Nothing Then
With eWB
.Activate
' process stuff
.Save
.Close
End With
Set eWB = Nothing
End If
eApp.Quit
Set eApp = Nothing
End Sub
I ran this from word and it worked, I think somehow you have an early binding problem, which is most likely is due to installing a new version of word on your machine. You can google it and clean your registry to get rid of it.
Sub Populate()
Dim eApp As Object
Dim eWB As Object
Dim eSheet As Object
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set eApp = CreateObject("Excel.Application")
End If
'Open Workbook
WorkbookName = "\\grid\sasprod\ci\reports\Quickmarks\Quickmarks Tables A.xlsx"
eApp.Visible = True
eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
eWB.Activate
End Sub

VBA copying from Excel file to WORD file bookmark

When I copy a chart from Excel ('Report' sheet) to a WORD file ('Report template.docx'), why does VBA wipe out the previous content of the WORD file? I suspect the problem is in line 'wddoc.Range.Paste' but I don't know how to change it to avoid the problem.
Sub ActivateWordTransferData()
Dim wdapp As Object, wddoc As Object
Dim strdocname As String
Set wdapp = GetObject(, "Word.Application")
wdapp.Visible = True
strdocname = "C:\users\ian\Documents\Dropbox\Report template.docx"
Set wddoc = wdapp.documents(strdocname)
Worksheets("Report").Shapes("Chart 2").Copy
wdapp.Activate
wddoc.bookmarks("bkmark4").Select
wddoc.Range.Paste
wddoc.Save
Set wddoc = Nothing
Set wdapp = Nothing
Application.CutCopyMode = False
End Sub
I'm not sure why the contents of the Word document are being overwritten.
However, removing the .Select operation and just pasting into the bookmark's range seems to work.
Remove these lines:
wddoc.bookmarks("bkmark4").Select
wddoc.Range.Paste
and replace with this line:
wddoc.bookmarks("bkmark4").Range.Paste

MS Access is ignoring my VBA code to export without headers

I have made a snippet of VBA code which exports two tables from MS Access 2010 into a new xlsx spreadsheet. I manually delete the spreadsheet before I run the code again.
The field names from my tables are exported into the spreadsheet as cell data. Which I DONT want.
In the code same below I've set one export property to true and one to false just to show it is exporting the same way for both. I have tried both false and both true as well.
public sub output
outputFileName as string
outputFileName = "J:\My Documents\testmycode.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Example1 Table", outputFileName, False
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "Example 2 Table", outputFileName, True
end sub
Any help is gratefully recieved!
This argument is not used by TransferSpreadsheet when exporting to EXCEL; it
always exports the field names regardless of what you put for this argument
in your code or macro. This argument works only for imports.
Maybe this would do it for you.
Public Function DeleteRowInExcel()
On Error GoTo Err_DeleteRowInExcel
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim MyFileName As String
MyFileName = "c:\temp\MyOutputFile.xls"
Set xlApp = CreateObject("Excel.Application")
Set wb = xlApp.Workbooks.Open(MyFileName)
Set ws = wb.Sheets(1)
ws.Cells(1, 1).EntireRow.Delete
wb.Save
Exit_DeleteRowInExcel:
'Close Excel
wb.Close savechanges:=False
xlApp.Quit
Set xlApp = Nothing
Set wb = Nothing
Set ws = Nothing
Exit Function
Err_DeleteRowInExcel:
MsgBox Err.Number & ", " & Err.Description, , "Error"
Resume Exit_DeleteRowInExcel
End Function