I am opening an excel workbook from excel and delete a sheet inside. I want to do this without the message from Excel:
"Excel will permanently delete this sheet, do you want to continue"
However I cannot make the "DisplayAlerts = False" work correctly.
Public Sub xportQuery()
Dim appExcel As Excel.Application
Dim myWorkbook As Excel.Workbook
Dim PathDaily, FileName As String
PathDaily = Forms!Menu!Text69
FileName = Forms!Menu!Text84
Set appExcel = CreateObject("Excel.Application")
Set myWorkbook = appExcel.Workbooks.Open(PathDaily & FileName)
appExcel.Visible = True
'Set appExcel = Nothing
Set myWorkbook = Nothing
appExcel.DisplayAlerts = False
Workbooks(FileName).Sheets("Sheety").Delete
appExcel.DisplayAlerts = True
End Sub
Writing it this way I get a "Subscript out of range" on the Sheets("Sheety").delete
If I take of the two DisplayAlerts lines, the code works but with the alert.
How do I write my code correctly to work without any alert message?
Note: DoCmd.SetWarnings didn t work either as the message is displayed in Excel
Thanks To Sam's Comment:
it works either by changing
Workbooks(FileName).Sheets("Sheety").Delete
into
myWorkbook.Sheets("Sheety").Delete
or
AppExcel.Workbooks(FileName).Sheets("Sheety").Delete
However the rest of the macro can still use Workbooks(Filename) without the "AppExcel." Reference
Related
I'm using Access VBA to auto update a shared Excel file - create XL object, open the shared file by sharepoint path, make necessary updates and close the file. In the codes, the displayalerts is set to False
Most of the time it works ok, but occasionally upon closing the file, it gives this prompt, even if the displayalerts is set to false.
When this happens, how do I auto select "Discard my change" by vba code?
Here's the code:
Dim XL As Excel.Application
Dim wkb As Excel.Workbook
Set XL = CreateObject("Excel.Application")
XL.Visible = False
XL.DisplayAlerts = False
Set wkb = XL.Workbooks.Open(SharePointFilePath)
'do stuff
wkb.Save
wkb.Close
XL.Quit
Set XL = Nothing
I'm currently trying to make a macro that opens a user defined excel spreadsheet, extracts some data for use in the word document and then closes it. My problem is that when I run the macro, the spreadsheet that I opened is still technically open as a background process in my task manager. I read on another stack overflow question that the reason is because visual basic will not release the reference object from excel until I close out of Microsoft Word. However, even after closing out of Word, the excel background process is still going and I can only stop it by ending the task in the task manager. To clarify, if I run the macro, close Word and then try to open the excel file, I can get in without telling me it's a read only file. However, if I don't close out of Word and I try to go into the spreadsheet after running the macro, then it tells me that it's a read only file. Below is the code I'm using that is causing this problem for me. Thanks to anyone who can help.
Sub UpdateProposal()
'Declares variables
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim SpreadsheetPath As String
Dim xlSheet As Excel.Worksheet
Dim xlRange As Excel.Range
Dim ExcelWasNotRunning As Boolean
Dim ProposalInfoArr(1 To 30) As String
'Skips to ErrorHandler if user cancels out of file dialog
On Error GoTo ErrorHandler
'Display a Dialog Box that allows to select a single file.
'The path for the file picked will be stored in SpreadsheetPath variable
With Application.FileDialog(msoFileDialogFilePicker)
'Makes sure the user can select only one file
.AllowMultiSelect = False
'Filter to just the following types of files to narrow down selection options
.Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
'Show the dialog box
.Show
'Stores in SpreadsheetPath variable
SpreadsheetPath = .SelectedItems.Item(1)
End With
'If Excel is running, get a handle on it; otherwise start a new instance of Excel
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set xlApp = New Excel.Application
End If
'If you want Excel to be visible, you could add the line: xlApp.Visible = True here; but your code will run faster if you don't make it visible
'Open the workbook
Set xlBook = xlApp.Workbooks.Open(FileName:=SpreadsheetPath)
'''Extracts Data
'Quits out of Excel if it was not running previous to running the macro.
If ExcelWasNotRunning Then
xlApp.DisplayAlerts = False
xlApp.Quit
End If
'Make sure you release object references.
Set xlRange = Nothing
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
'Ends the macro before the error handler
Exit Sub
'Ends Macro
ErrorHandler:
MsgBox "The following error occurred: " & Err.Description
End Sub
You are defining the objects correctly:
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim xlRange As Excel.Range
but you forgot about the implicitly used Workbooks object... as most of the answers you will find do... which means it doesn't get released. So do it like this:
Dim SpreadsheetPath As String
Dim xlApp As Excel.Application
Dim xlBooks As Excel.Workbooks
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim xlRange As Excel.Range
SpreadsheetPath = "C:\MyPath\MyFile.xlsx"
Set xlApp = New Excel.Application
' Set xlApp = GetObject(, "Excel.Application") ' or attach to an existing one
Set xlBooks = xlApp.Workbooks
Set xlBook = xlBooks.Open(FileName:=SpreadsheetPath) ' you can use .Add instead if someone else may have it open already
Set xlSheet = xlBook.Worksheets(1)
Set xlRange = xlSheet.Range("A1")
' do stuff with the worksheet/range
xlRange.Value = "foo"
' the order matters
' just like it does
' when you create the objects
Set xlRange = Nothing
Set xlSheet = Nothing
xlBook.Close False
Set xlBook = Nothing
Set xlBooks = Nothing
xlApp.Quit
Set xlApp = Nothing
However, you may find that it still isn't getting released when you want, but it will get released when you close the program you are using to create it (in your case, MS-Word) as that is (presumably) when Windows does its built-in garbage collection.
Note: I removed the error handling just to keep it a clean example, but you can leave that in
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
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.
I have a vba macro to open excels and read data.
Dim xlApp As Excel.Application
Set xlApp = CreateObject("Excel.Application")
Set excelworkbook = xlApp.Workbooks.Open(file_path, ReadOnly:=True, notify:=False)
And error "Too many different cell formats" occurred on the third line. I assume it's because of cell formats(fonts, borders, etc.) and does anyone know how to resolve this issue programmatically? No error is raised when I try to open the excel manually. Any advice would be appreciated.
Instead of your code, try doing it this way:
Dim excelWorkbook As Excel.Workbook
Set excelWorkbook = Excel.Workbooks.Open(file_path, ReadOnly:=True, Notify:=False)
If it still gives you trouble, maybe adding these will help:
Application.DisplayAlerts = False
' Application.ScreenUpdating = False ' Optional, might not be necessary.
Just remember to set them back to their defaults afterwards.