VBA to get open Excel Binary Workbook - excel

I have an MS Access form that opens an Excel binary file (.xlsb) from another website. I am trying to check all the user's open Excel files so that I work on the correct workbook.
By running the loop below on the opened, but not saved Excel file, the GetObject does not find the just opened workbook. This code does find other Excel files that I might already have open.
But, if I save the Excel file that I opened from the network, close and reopen it before I try to find the open Excel files with the code below, the code finds that file too.
Is there a better way for me to capture the just-opened file name? On the new Excel file, I need to filter data from particular Excel tabs and add that data to Access tables.
Dim xlApp As Excel.Application
Dim strWBList As String
strWBList = ""
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err.Number = 0 Then
Dim xlWB As Excel.Workbook
For Each xlWB in xlApp.Workbooks
If Len(strWBList) > 0 Then
strWBList = strWBList & ","
End If
strWBList = strWBList & xlWB.Name
Next xlWB
Set xlApp = Nothing
Set xlWB = Nothing
End If
MsgBox strWBList

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

Activating opened Excel workbook from Outlook

I have a macro in my Outlook that whenever I receive an e-mail with a certain subject, it automatically opens an Excel workbook and pastes a portion of the e-mail subject in a specific cell in one of the worksheets. It works perfectly. Now I need to do this exact same process but pasting this information in an already opened workbook, instead of opening a closed file.
I've tried different solutions from my limited Excel VBA knowledge (ActiveWorkbook, worbooks(filename).activate, etc.) but none of that worked and I have not found anything similar online, as most macros are written as being run from an Excel file and not Outlook.
This is part of our current code, that opens the file and pastes the e-mail subject (which is the "ticker" value) in a specific cell on the "Lista Empresas" worksheet. What I need is a code that does the same, but in an workbook that is already opened (let's call it "test1").
Dim exapp As Excel.Application
Dim ExWbk As Workbook
Dim ExWbk2 As Workbook
Set exapp = New Excel.Application
Set ExWbk2 = exapp.Workbooks.Open("\\XXX\ListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
exapp.Visible = True
ExWbk2.Sheets("Lista Empresas").Range("P2").Value = ticker
ExWbk2.Sheets("Lista Empresas").Range("P3").Calculate
There are a few scenarios to handle here. First, is Excel running? If no, then do what you are doing already. If yes - is the correct workbook open? If yes - return it, otherwise open it.
Dim ExWbk2 As Workbook
Dim wb As Workbook
Dim exapp As Excel.Application
On Error Resume Next
Set exapp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set exapp = Nothing
End If
On Error GoTo 0
If exapp Is Nothing Then
' Excel is not running
Set exapp = New Excel.Application
Set ExWbk2 = exapp.Workbooks.Open("\\XXX\ListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
ExWbk2.Visible = True
Else
' Excel is running, but is the right book open?
For Each wb In exapp.Workbooks
Debug.Print wb.Name ' <-- This will help you find what to look for
If wb.Name = "ListaEmpresas_ajustado" Then
' Yes, it is!
Set ExWbk2 = wb
End If
Next
If ExWbk2 Is Nothing Then
' No, it wasn't
Set ExWbk2 = exapp.Workbooks.Open("\\XXX\ListaEmpresas_ajustado.xlsm", UpdateLinks:=0)
End If
End If
The trick to find out if Excel is running is GetObject. It will fail if it can't find it.
The for loop is there to allow for finding the correct workbook, based on the name. Adjust as needed.
The following code gets the object if you know the name of the sheet currently active in Excel instance. I guess this could be got from the application title using the first bit of code.
Dim exapp As Excel.Application
Dim ExWbk As Workbook
Dim ExWbk2 As Workbook
Set exapp = GetObject("ListaEmpresas_ajustado.xlsm").Application
exapp.Visible = True
ExWbk2.Sheets("Lista Empresas").Range("P2").Value = ticker
ExWbk2.Sheets("Lista Empresas").Range("P3").Calculate

How to open Excel if not already open

I'm trying to find a way to open Excel using Outlook VBA, but only if it's not already open. I managed to find some code on the internet that opens Excel, does changes and then closes it, but it doesn't behave nicely if the Excel workbook is already open(it does apply the changes, but it no longer closes the Excel workbook, and it simply leaves it with a grey interior; also, sometimes it doesn't even show in the explorer anymore and I have to close it from the task manager).
I would also greatly appreciate if someone could explain what most of the code does.
Public xlApp As Object
Public xlWB As Object
Public xlSheet As Object
Sub ExportToExcel()
Dim enviro As String
Dim strPath As String
'Get Excel set up
enviro = CStr(Environ("USERPROFILE"))
'the path of the workbook
strPath = enviro & "\Documents\test2.xlsx"
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err <> 0 Then
Application.StatusBar = "Please wait while Excel source is opened ... "
Set xlApp = CreateObject("Excel.Application")
bXStarted = True
End If
On Error GoTo 0
'Open the workbook to input the data
Set xlWB = xlApp.Workbooks.Open(strPath)
Set xlSheet = xlWB.Sheets("Sheet1")
' Process the message record
On Error Resume Next
xlWB.Close 1
If bXStarted Then
xlApp.Quit
End If
End Sub
I know what the xlWb and xlSheet objects do, and how they're declared, and I also understand what the environ function and strPath string do, but I don't undestand why we need the bXStarted boolean, what Set xlApp = GetObject does, why the Application.StatusBar message doesn't get displayed, the difference between GetObject and CreateObjectand why so many error tests are needed.
Thanks in advance.
The difference between get object and create object is in the title, one will get open excel.application, if there is an error err<>0 then it creates an excel.application. I think you'll be getting a saveas message, as the file may not be saving, but open, and you're instructing it to save, the error resume next is skipping it . Try saving before just a .close If you remove the on error resume next the error wont be skipped and will be shown.
Sub explaination()
Dim blnDidICreateExcel As Boolean ' Please read MSDN on boolean
Dim objToHoldExcelCreatedOrNot As Object ' Please read MSDN on objects create/get
' Does the user have Excel open, if i try to get it, then there will be an error logically if not
Set objToHoldExcelCreatedOrNot = GetObject(, "Excel.Application")
' Was there an error
If Err <> 0 Then
' There was, so i need to create one
Set objToHoldExcelCreatedOrNot = CreateObject("Excel.Application")
blnDidICreateExcel = True ' Yes, i created it
End If
' Do the neccessary
' CLose the workbook
' Did i create this Excel, if so tidy up
If blnDidICreateExcel Then objToHoldExcelCreatedOrNot.Quit
End Sub

Reference and access Excel from Outlook

I'm trying to update an Excel file from Outlook (Office 2010). How do I reference and access Excel?
As a simple test I'm trying to count the number of open workbooks. When I run this I get 0, even though there are 2 open.
Sub Test()
Dim xlApp As Excel.Application
Dim xlWBook As Excel.Workbook
Set xlApp = New Excel.Application
Debug.Print "xlApp.Workbooks.Count = " & xlApp.Workbooks.Count
On Error Resume Next
Set xlWBook = xlApp.Workbooks("Data.xlsx")
Err.Clear 'Clear error and open File Index
If xlWBook Is Nothing Then
Set xlWBook = xlApp.Workbooks.Open("C:\Users\Chris\Desktop\Data.xlsx")
End If
End Sub
This is what I use to detect Excel:
Dim xlApp As excel.Application
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err.Number = 429 Then 'Excel not running
Set xlApp = CreateObject("Excel.Application")
End If
On Error GoTo 0
once xlApp is set, you can use xlApp.Workbooks.Count to count the worksheets
Note: This code will get the first one opened, if there are more than one instance of Excel to find
If you have to find a specific workbook, from this page, Set xlApp = GetObject("Book2").Application will find the workbook, even if it's not in the first instance. If the workbook is from a file, or already saved, replace book2 with the full path and filename - Side effect - this will also open the file if it is not already open
More usage info: http://msdn.microsoft.com/en-us/library/aa164798%28v=office.10%29.aspx

VBScript code to keep Excel file open

I have a VBScript code to open an excel file, run a macro and close it. Fine.
Now, the only thing I want to change is to leave the file open.
If I remove the 2 lines of code xlApp.activewindow.close and xlApp.Quit, then the workbook and the application are closed anyway, but they remain open in the background (Excel process still active in Task Manager). Hence, it is impossible to re-run the macro later on the same file by calling the script again (which is exactly what I want to do).
Why?
Here is the code:
Option Explicit
On Error Resume Next
MyTest
Sub MyTest()
Dim xlApp
Dim xlBook
Dim fpath
Dim fname
' Excel application running? if not, open Excel
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If xlApp <> "Microsoft Excel" Then
Set xlApp = CreateObject("Excel.Application")
End If
Err.Clear
' correct Excel file open? if not, open it
fpath = "D:\Desktop\"
fname = "MyTest.xls"
xlApp.Workbooks(fname).Activate
If Err = 0 Then
' no error, so it has been possible to activate the workbook
Set xlBook = xlApp.Workbooks(fname)
Else
' unable to activate, so workbook was not open -> open it now
Set xlBook = xlApp.Workbooks.Open(fpath & fname, 0, True)
End If
Err.Clear
' now run the desired macro in the excel file
xlApp.Run "HelloWorld"
' WANT TO CHANGE THIS
xlBook.saved = True
xlApp.activewindow.close
' AND THIS
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
You just need to make your new instance of Excel visible. Do this right after creating it:
xlApp.Visible = True
This line of code will close your current activated workbook (by now, it is D:\Destop\MyTest.xls);
xlApp.activewindow.close
This line will quit Excel application;
xlApp.Quit

Resources