Using Access 2010 VBA list all open Excel Workbooks - vba

Ok, I must be missing something subtle here.
In Excel 2010 this VBA works:
Private Sub ExcelTest()
Dim wb As Workbook
For Each wb In Workbooks
Debug.Print wb.Name
Next wb
End Sub
I'm trying to replicate this in Access VBA and I've tried the following approaches in Access 2010 with no success.
Private Sub AccessTest1()
'Derived from http://stackoverflow.com/questions/15958061/controlling-excel-
'workbook-from-access-2010-vba
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Set xlApp = New Excel.Application
For Each xlWB In Excel.Workbooks
Debug.Print xlWB.Name
Next xlWB
'Nothing happens.
'Stepping through and hovering:
'xlApp = "MicroSoft Excel"
'xlWB = Nothing
'xlWB.Name = Object variable or With block variable not set.
'But doesn't throw an error.
End Sub
Private Sub AccessTest2()
'Derived from http://stackoverflow.com/questions/5729195/how-to-refer-to-excel-
'objects-in-access-vba
Dim xlApp As Excel.Application
Dim wb As Excel.Workbook
Set xlApp = New Excel.Application
For Each wb In Excel.Workbooks '<--- Like this nothing happens
Debug.Print wb.Name
Next wb
'Stepping through and hovering:
'xlApp = "MicroSoft Excel"
'wb = Nothing
'wb.Name = Object variable or With block variable not set. But doesn't throw an error.
For Each wb In xlApp.Workbooks '<--- This throws a "Object variable or
'With block variable not set" error
Debug.Print wb.Name
Next wb
End Sub
Private Sub AccessTest3()
'Derived from http://stackoverflow.com/questions/5729195/how-to-refer-to-excel-
'objects-in-access-vba
Dim objExcelApp As Object
Dim wb As Object
Set objExcelApp = CreateObject("Excel.Application")
Set wb = objExcelApp.Workbook '<--- Throws "Object doesn't support this property
'or method error"
'Hovering after error:
'objExcelApp = "MicroSoft Excel"
'wb = Nothing
For Each wb In objExcelApp.Workbooks
Debug.Print wb.Name
Next wb
End Sub
I definitely have the "Microsoft Excel 14.0 Object Library" reference checked in Access.
I'm just trying to list any open Excel Workbooks so that I can then act against that information.
Thanks for your help in advance.

Set xlApp = New Excel.Application creates a new instance of Excel - and of course you do not have any workbooks in there.
What you want to achive is to go thru an already opened Excel instance. Therefore you have to use getObject().
Another Error is in your For statement ... you have to use xlApp.Workbooks instead of Excel.Workbooks.
The following code should provide the exprected result:
Dim xlApp As Excel.Application
Set xlApp = GetObject(, "Excel.Application")
Dim xlWB As Excel.Workbook
For Each xlWB In xlApp.Workbooks
Debug.Print xlWB.Name
Next xlWB
Set xlApp = Nothing
Set xlWB = Nothing
Please keep also in mind to destry object variables on the end by setting them to Nothing.

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.

Need to get the last worksheet name in msgbox

I need to get the last (rightmost worksheet) name in msgbox.
I used Sheets(Sheets.Count) to get last sheet. But its only giving first sheets name. Kindly help me on this.
Here is my code.
Sub ShowMRNumber()
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Open("location")
Set xlSheet = xlApp.Sheets(Sheets.Count)
MsgBox "MR No. is" & vbNewLine xlSheet.Name
xlApp.Workbooks.Close
End Sub
Your line saying
Set xlSheet = xlApp.Sheets(Sheets.Count)
should actually be
Set xlSheet = xlBook.Sheets(xlBook.Sheets.Count)
Using xlApp.Sheets is probably not an issue, as that would probably have defaulted to the active workbook within the xlApp instance of Excel, but Sheets.Count (without a xlApp or xlBook qualifier) would not have been referring to a workbook open in a different instance of Excel - it would have been referring to the active workbook in the instance of Excel where the code was running.

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

Creating Excel Files using VB2010

I have a form with 1 button to create an Excel file on my desktop.
I get error message:
NullReferenceException Was Unhandled
Object reference not set to an instance of an object
and it highlights the code:
WB = excelapp.workbooks.add
I did add the reference "Microsoft excel 14.0" and my full code is below:
imports excel = microsoft.office.interop.excel
dim excelapp as excel.application
dim WB as excel.workbook
sub button1()
WB = excelapp.workbooks.add
excelapp.visible=true
end sub
Missing New on your Excel instance for starters:
Dim xlApp As New Excel.Application
Dim xlWorkbook As Excel.Workbook = xlApp.Workbooks.Add()
Dim xlWorksheet As Excel.Worksheet = CType(xlWorkbook.Sheets("sheet1"), Excel.Worksheet)
xlWorksheet.Cells(1, 1) = "data in first cell"
xlWorksheet.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\" & "Test.xlsx")
xlWorkbook.Close()
xlApp.Quit()
xlApp = Nothing
xlWorkBook = Nothing
xlWorkSheet = Nothing
You should probably put this in Try/Catch/Finally block to catch errors in case you run into issues, but mostly because if the program doesn't continue properly finish that code block, an EXCEL.EXE will remain open in your task manager, as well as whatever Excel file it was accessing will be "in use by another program" when you try to access/modify/delete it.
just add one line, then it'll work
imports excel = microsoft.office.interop.excel
dim excelapp as excel.application
dim WB as excel.workbook
sub button1()
excelapp = new excel.application
WB = excelapp.workbooks.add
excelapp.visible=true
end sub

Procedure opens multiple instances of Excel

I wrote the following procedure to check for Microsoft Excel application, if opened. The procedure works fine, except that once it opens the workbook and the activates the sheet, a second instance of Excel tries to open.
Here is my code:
Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook
Dim xlWBName As String = "2011.1004.Compensation Template"
For Each p As System.Diagnostics.Process In System.Diagnostics.Process.GetProcesses()
If p.ProcessName <> "EXCEL" Then
xlApp.Visible = True
xlBook = xlApp.Workbooks.Open("F:\Test Environment\Compensation Workbook\Compensation Workbook\bin\Debug\" & xlWBName & ".xlsx")
Dim xlSheet As Excel.Worksheet
xlSheet = CType(xlBook.Sheets("SummaryWorksheet"), Worksheet)
xlSheet.Activate()
End If
Next
Use the GetObject method to find an already open Application object:
http://msdn.microsoft.com/en-us/library/e9waz863(v=vs.90).aspx
Dim xlApp As Excel.Application
Try
'get an existing excel.application object
xlApp = GetObject(, "Excel.Application")
Catch ex As Exception
'no existing excel.application object - create a new one
xlApp = New Excel.Application
End Try
Dim xlBook As Excel.Workbook
Dim xlWBName As String = "2011.1004.Compensation Template"
xlApp.Visible = True
xlBook = xlApp.Workbooks.Open("F:\Test Environment\Compensation Workbook\Compensation Workbook\bin\Debug\" & xlWBName & ".xlsx")
Dim xlSheet As Excel.Worksheet
xlSheet = CType(xlBook.Sheets("SummaryWorksheet"), Worksheet)
xlSheet.Activate()