Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    Visual Basic




How To Close Excel


Hi there,I wrote an application that reads data from an excelsheet (importfilter), using the following code to open the file: Dim objExcelApp as new Excel.Application Dim objExcelBook as Excel.Workbook Call objExcelApp.Workbooks.Open(strFileName) set objExcelBook = objExcelApp.ActiveWorkbookWhen the application is terminated, I want to close the excel-instance too, but it just doesn't work. Even if I use Unload objExcelApp Unload objExcelBookthere is still the excel-task in the task mangager.How can I close it totally?Thanks in advance,Daniel




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
Not Close Thead When I Close Excel
I have developed, a .net dll. I call this dll from excel VBA code. In dll code I throw a thread. I need the thread still is running when I close Excel. How can I do it?
Thanks


________________
Hip Hop Videos
Foro Heavy

Whats The Vb Code To Close Excel Within Excel Using A Macro
i need the code to close excel within excel using a macro and saving all of the changes.


please help//


Jas

Close All Excel Applications Before Start New Excel Application
Ciao Gurus,

I created an excel 2003 application which takes time to be opened.
I notice that it is more fast (50-60%) if no other excel applications are opened, so here the question: is it possible to close all excel application before start my excel application?
Of course not manually

Best Regards
kaiala


 

Can't Close Excel Instance After Excel Automation
I hope I'm posting this in the right forum, I've never really used on of these forums before.  I have the following code that I am using to move date from MS Access to MS Excel.  The code itself work flawlessly except the after closing there is still an instance of Excel hanging around in my task manager.  I believe the problem is related to the fact that the row I activated to use the .freezePanes is still activated when I close the application.  If I remove the adding of the image and the freezePane there is no Excel instances left.  If I put them back in then it hangs there.  I've scoured the net for about a week looking for my error and I've yet to find it.  Any suggestions would be appriciation.

Code Starts here:

Sub ecMAP()
On Error GoTo ErrHandler
   
   ' Excel object variables
   Dim appExcel As Excel.Application
   Dim wbk As Excel.Workbook
   Dim wks As Excel.Worksheet
   Dim sOutput As String
   
   Dim dbs As DAO.Database
   Dim rst As DAO.Recordset
   Dim sSQL As String
   Dim lRecords As Long
   Dim iRow As Integer
   Dim iCol As Integer
   Dim iFld As Integer
   Dim highLight As Boolean
   Dim sheetsPerBook As Integer
         
   'CONSTANTS
   Const aTab As Byte = 1
   Const aStartRow As Byte = 6
   Const aStartColumn As Byte = 1

   ' set to break on all errors
   Application.SetOption "Error Trapping", 0

   ' GENERATING OUTPUT FILE NAME
   If formdate("S", 8) = formdate("E", 8) Then
   
        sOutput = "S:HWYREPORTSCOLAccountsMMarianiMariani Accessorials " & Format(fdate(formdate("S", 8)), "mm-dd-yy") & ".xls"
   
        Else
   
        sOutput = "S:HWYREPORTSCOLAccountsMMarianiMariani Accessorials " & Format(fdate(formdate("S", 8)), "mm-dd-yy") & " through " & Format(fdate(formdate("E", 8)), "mm-dd-yy") & ".xls"
   
   End If
      
   If Dir(sOutput) <> "" Then Kill sOutput
      
   ' Create the Excel Applicaiton, Workbook and Worksheet and Database object
   Set appExcel = New Excel.Application
   sheetsPerBook = appExcel.SheetsInNewWorkbook
   appExcel.SheetsInNewWorkbook = 1
   Set wbk = appExcel.Workbooks.Add
   appExcel.SheetsInNewWorkbook = sheetsPerBook
   Set wks = wbk.Worksheets(aTab)
   Set dbs = CurrentDb
   sSQL = "select * from MAPqryExport"
   Set rst = dbs.OpenRecordset(sSQL, dbOpenSnapshot)
   
   'ADDING LOGO TO EXCEL FILE

        wks.Pictures.Insert("S:HWYREPORTSLibrariesLogosmariani.GIF").Select
        Selection.ShapeRange.Height = 49.5
        Selection.ShapeRange.Width = 235.5
    
            With Selection
                .Placement = xlFreeFloating
                .PrintObject = True
            End With
 
    wks.Rows("6").Activate
    ActiveWindow.FreezePanes = True
    
   ' ADDING COLUMN HEADERS TO EXCEL FILE
   
   With wks
   
        iCol = aStartColumn
        iRow = (aStartRow - 1)
   
        If Not rst.BOF Then rst.MoveFirst
   
            iFld = 0
            lRecords = lRecords + 1
      

                For iCol = aStartColumn To aStartColumn + (rst.Fields.Count - 1)
            
                    wks.Cells(iRow, iCol) = rst.Fields(iFld).Name
                    wks.Cells(iRow, iCol).Interior.ColorIndex = 1
                    wks.Cells(iRow, iCol).Font.ColorIndex = 2
                    wks.Cells(iRow, iCol).Font.Bold = True
                        
                    iFld = iFld + 1
        
                Next
              
                    iRow = iRow + 1
                    rst.MoveNext

    End With
    
   ' ADDING INFO TO EXCEL FILE
   iCol = aStartColumn
   iRow = aStartRow
   highLight = False
   
   With wks
   
        If Not rst.BOF Then rst.MoveFirst
        Do Until rst.EOF
            iFld = 0
            lRecords = lRecords + 1
         
      For iCol = aStartColumn To aStartColumn + (rst.Fields.Count - 1)
            
            wks.Cells(iRow, iCol) = rst.Fields(iFld)
            wks.Cells(iRow, iCol).NumberFormat = "$0.00"
                       
            'If highLight = True Then
            
                'wks.Cells(iRow, iCol).Interior.ColorIndex = 35
            
            'End If
                            
            iFld = iFld + 1
        
                Next
              
                    iRow = iRow + 1
                    rst.MoveNext
                    
                    'If highLight = False Then
                    
                        'highLight = True
                        
                            'Else
                                
                                'highLight = False
                    'End If
   
   Loop
   
   End With
   
   'ADDING TOTALS
   
   Dim columnCount As Integer
   columnCount = 3      'starting column for totals
   
   With wks
   
        wks.Cells(aStartRow + rst.RecordCount + 1, aStartColumn + 1) = "Totals:"
        wks.Cells(aStartRow + rst.RecordCount + 1, aStartColumn + 1).Font.Bold = True
        wks.Cells(aStartRow + rst.RecordCount + 1, aStartColumn + 1).Font.ColorIndex = 2
        wks.Cells(aStartRow + rst.RecordCount + 1, aStartColumn + 1).Interior.ColorIndex = 1
   
            Do While columnCount <= 10
   
                wks.Cells(aStartRow + rst.RecordCount + 1, columnCount).Formula = "=SUM(R[-" & rst.RecordCount + 1 & "]C:R[-1]C)"
                wks.Cells(aStartRow + rst.RecordCount + 1, columnCount).Font.Bold = True
                wks.Cells(aStartRow + rst.RecordCount + 1, columnCount).Font.ColorIndex = 2
                wks.Cells(aStartRow + rst.RecordCount + 1, columnCount).Interior.ColorIndex = 1
   
                columnCount = columnCount + 1
        
   Loop
   
   End With
   
   'AUTOFITTING COLUMNS
   
   With wks
   
        wks.Columns("A:A").EntireColumn.AutoFit
        wks.Columns("B:B").EntireColumn.AutoFit
        wks.Columns("C:C").EntireColumn.AutoFit
        wks.Columns("D:D").EntireColumn.AutoFit
        wks.Columns("E:E").EntireColumn.AutoFit
        wks.Columns("F:F").EntireColumn.AutoFit
        wks.Columns("G:G").EntireColumn.AutoFit
        wks.Columns("H:H").EntireColumn.AutoFit
        wks.Columns("I:I").EntireColumn.AutoFit
        wks.Columns("J:J").EntireColumn.AutoFit
        wks.Columns("K:K").EntireColumn.AutoFit
        wks.Columns("L:L").EntireColumn.AutoFit
        wks.Columns("M:M").EntireColumn.AutoFit
        wks.Columns("N:N").EntireColumn.AutoFit
        wks.Columns("O:O").EntireColumn.AutoFit
        wks.Columns("P:P").EntireColumn.AutoFit
        wks.Columns("Q:Q").EntireColumn.AutoFit
        wks.Columns("R:R").EntireColumn.AutoFit
   
    End With
    
   With wbk
   
        'NAMING TAB
        wks.Select
        wks.Name = "Mariani Accessorials"
        
   End With
      
   With wks

    .PageSetup.Zoom = False
    .PageSetup.CenterHeader = "Mariani Accessorial Report"
    .PageSetup.CenterFooter = "Page &p"

   End With
   
'CLOSING AND SAVING NEW FILES
           
    Set wks = Nothing
    
    wbk.SaveAs FileName:=sOutput, FileFormat:= _
            xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
            , CreateBackup:=False
    
    wbk.Close SaveChanges:=False

    Set wbk = Nothing
        
    appExcel.Quit
        
    Set appExcel = Nothing

   'Call AutoEmailAll("SPNEM - tblDistList", "Attached is the SP News Exception Report.  If the report is blank, there were no exceptions entered.", "SP News Exception Memo Report", sOutput)
   
ExitProcedure:
    Exit Sub

ErrHandler:
    Select Case Err.Number
        Case Else
            Call UnexpectedError(Err.Number, "ecSPNEM:  " _
                    & Err.Description, Err.Source, _
                    Err.HelpFile, Err.HelpContext)
            Resume ExitProcedure
            Resume
    End Select
   
   
   End Sub


Excel, To Close Or Not To Close
Hello All,

I have a VB6 app that can open different Excel sheets. At some point after the user selects these sheets, Excel starts acting strange. Meaning Excel opens, but only the toolbar can be seen.

I will post my code being I know everyone will think early binding problems, but i can't find anything out of whack.

Also, I didn't use .QUIT being i want the user to be able to print or modify the sheet if needed. At this point, if the user opens some other sheet on there pc, Excel doesn't cooperate. I guess I would like to get rid of EXCEL.EXE in the task mgr once the user closes Excel, but it seems to hold the lock until my VB app is closed.

Any ideas????


Code:
'Code
Dim xlApp As excel.Application 'excel
Dim xlBook As excel.Workbook 'excel
Dim xlSheet As excel.Worksheet 'excel
Dim spMnth, spDay, spYear, spDate As String

Set xlApp = Nothing
Set xlBook = Nothing
Set xlSheet = Nothing

Set xlApp = excel.Application
Set xlBook = GetObject("C:EstSysRptssp_req.xls") ' production
Set xlSheet = xlBook.Worksheets(1)
xlApp.ScreenUpdating = True
xlBook.Application.Visible = True
xlBook.Windows(1).Visible = True
xlBook.Application.Cursor = xlWait
xlBook.Application.StatusBar = "***Building Excel Sheet - Please Wait***"

Set rsSP = gDatabase.OpenRecordset("Select * from [Special Pricing Request] Where PROPNO = " & SelJobNo, dbReadOnly)
With rsSP
xlSheet.Cells(2, "I") = 1 'Page Number
xlSheet.Cells(6, "C") = !branch
xlSheet.Cells(7, "C") = !JobName
xlSheet.Cells(8, "C") = !city & ", " & !State
xlSheet.Cells(9, "C") = !PROPNO
xlSheet.Cells(6, "I") = !slsname
xlSheet.Cells(7, "I") = !req_dt
xlSheet.Cells(9, "I") = !BID_DT
xlSheet.Cells(10, "I") = spDate

'Product Check Boxes
xlSheet.Cells(14, "A") = IIf(!PRD1 = True, " ___X___ ", " _______ ")
xlSheet.Cells(15, "A") = IIf(!PRD2 = True, " ___X___ ", " _______ ")
xlSheet.Cells(16, "A") = IIf(!PRD3 = True, " ___X___ ", " _______ ")
xlSheet.Cells(17, "A") = IIf(!PRD4 = True, " ___X___ ", " _______ ")
xlSheet.Cells(18, "A") = IIf(!PRD5 = True, " ___X___ ", " _______ ")

'Competition Check Boxes
xlSheet.Cells(28, "A") = IIf(!COMP1 = True, " ___X___ ", " _______ ") 'Simplex
xlSheet.Cells(29, "A") = IIf(!COMP2 = True, " ___X___ ", " _______ ") 'EST
xlSheet.Cells(30, "A") = IIf(!COMP3 = True, " ___X___ ", " _______ ") 'HoneyWell

xlSheet.Cells(11, "I") = spDate
xlSheet.Cells(14, "I") = !TSell
xlSheet.Cells(15, "I") = !GM_PCT
xlSheet.Range("F" & 37).Formula = "= (100 - SUM(F28:F36))"

'Protect the sheet after all data is transferred.
Screen.MousePointer = vbDefault
xlBook.Application.Cursor = xlDefault
xlBook.Application.StatusBar = "Ready"
xlSheet.Protect ("Pass")
If Dir("C:Progra~1Estima~1SP_REQ" & !PROPNO & ".xls") <> "" Then Kill ("C:Progra~1Estima~1SP_REQ" & !PROPNO & ".xls")
xlBook.SaveAs ("C:Progra~1Estima~1SP_REQ" & !PROPNO & ".xls")
If EMailClick = True Then
holdPropNo4Mail = !PROPNO
holdJobName4Mail = !JobName
xlApp.Quit 'Quit Excel if report is sent through email.
End If

Set xlApp = Nothing
Set xlBook = Nothing
Set xlSheet = Nothing
End With

Close Excel As Well?
Hello, Everyone:
I tried to get "Do you want to save" dialog like this by clicking X:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Dim thisWkBook As Workbook

Set thisWkBook = ThisWorkbook
thisWkBook.Close savechanges:=False
End Sub

Now,Dialog is gone. However, the excel is still there. I need to click X once more to get rid of the Excel. Can someone help me to get Excel as well when I click X once.
Thank you very much!
Charlie

'close' Help In Excel
Hi,

Is there anyway of stopping the user from clicking on the "X" close button in the top right-hand corner of the screen. I want the user to exit my form by pressing a command button, and I do not know how to disable the "X" button?

Excel Won't Close
I am trying to make a graph in Excel using vb 6. The problem is that when I run the code Excel stays open. If I don't use the line highlighted in red then there is no problem.

Private Sub Command2_Click()

Dim oWorkbook As Excel.Workbook
Dim oSheet As Excel.Worksheet
'
Set oExcel = New Excel.Application

oExcel.Workbooks.Open FileName:="C:Documents and Settings" & SpreadSheet & ".xls"

oExcel.Charts.Add
' Note the type
'.Columns("A:B").Select
oExcel.ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
oExcel.ActiveChart.HasTitle = True
oExcel.ActiveChart.ChartTitle.Characters.Text = "Total Number of Operations per Team"

oExcel.ActiveChart.SetSourceData Source:=Sheets("Sheet1").Range("A1:B1"), PlotBy:=xlColumns
' Note the location
oExcel.ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="MySheetName" & " Chart"
'End With

Set oSheet = Nothing
Set oWorkbook = Nothing
oExcel.Quit
Set oExcel = Nothing
end sub

How To Close Out Excel
Hi,

I'm trying to write code so that will direct Excel to close itself...

I have a piece of code that closes out a workbook but i'm not sure how to close out Excel?

My code looks like,


Application.DisplayAlerts = wdAlertsNone
Windows("Urine Macro.xls").Activate
ActiveWorkbook.Close
Application.DisplayAlerts = wdAlertsAll

Any ideas would be greatly appreciated.
Thanks

How To Close Excel Vb
can i put a close button in excel vb to close vb once it has run

and can i put in a cell in excel to run vb
cheers
Doug uk

Excel Will Not Close With VB6
I have a VB6 program that populates comboboxes from data with an Excel worksheet. But when I exit the VB program, in the Task Manager Excel is still running, sometimes many times. I have the Excel sheet opening at Load() and I want to have Excel exit when I unload the program. I need the Excel sheet to be opened until the program is ended. Everything works how it should except for the Excel sheet not closing. So how do I fix this?


Code:
Private Sub Form_Load()

Dim MyXLApp As New Excel.Application 'declare and start a new excel application
'Open an Excel workbook
MyXLApp.Workbooks.Open FileName:="M:material_strength_list_1.xls"

For y = 2 To 4 Step 1
cmb_mat.AddItem Sheets("Main").Cells(y, 1)
Next y

For v = 2 To 6 Step 1
cmb_temp.AddItem Sheets("Main").Cells(v, 2)
Next v

End Sub

Private Sub Form_Unload(Cancel As Integer)
Dim ans As Integer
Dim MyXLApp As New Excel.Application
ans = MsgBox("Do you really want to exit?", vbYesNo, "Exit Confirmation")
If ans = vbYes Then
MyXLApp.Quit
Set MyXLApp = Nothing

End
End If
End Sub

Excel Won't Close From VB6
From VB6 I open excel add a workbook, write to it, save the workbook, close the workbook, quit the application.
BUT: excel stays open in the task manager. If I run it again I get an error msg.

Public Sub OpenExcel()
On Error GoTo OpenError
Set xlApp = New Excel.Application
Set xlBook = xlApp.Workbooks.Add
Set xlSheet = xlBook.Worksheets.Add
xlSheet.Name = "Imported"
bExcelOpen = True
On Error GoTo 0
Exit Sub
OpenError:
MsgBox "Error opening Excel Spreadsheet" & vbCrLf & _
"Error: " & Error, vbCritical, "Open Error"
On Error GoTo 0
bExcelOpen = False
End Sub

Public Sub CloseExcel()
' Save the Sheet
On Error GoTo ExcelCloseError
xlSheet.Application.DisplayAlerts = False
xlSheet.SaveAs App.Path & "Scrap" & sName
xlSheet.Application.DisplayAlerts = True
xlBook.Close
' Close Microsoft Excel with the Quit method.
xlApp.Quit
' Release the objects.
Set xlSheet = Nothing
Set xlBook = Nothing
Set xlApp = Nothing
bExcelOpen = False
Exit Sub
ExcelCloseError:
MsgBox "Error closing Excel Spreadsheet" & vbCrLf & _
"Error: " & Error, vbCritical, "Shutdown Error"
On Error GoTo 0
bExcelOpen = True
End Sub

Thanks

Excel Won't Close
I am having a problem with Excel not closing even after I give the quit command. In the task manager the process is still running. This is causing my application to hang. Could anyone help me out? Here is my code:


Code:
Private Sub cmdCrtRpts_Click()
Dim nx As Integer
Dim nx2 As Integer 'checks to see that all fields are filled out.
nx = 0
nx2 = 0 '0=fields missing 1=all fields filled in correctly
Do Until nx = 13
If txtJobInfo(nx) <> "" Then
nx = nx + 1
Else
nx2 = 0
MsgBox "All fields must be filled out to create a report!", , "Empty field error"
Exit Sub
End If
Loop
'all fields filled out
'MsgBox "report will be created"
'************************Create Excel Report********************
Dim objExcel As Excel.Application
Dim objWB As Excel.Workbook
Dim objRC As Excel.Worksheet ' report cover
Dim objRng As Excel.Range
Dim excel_filename As String
Dim cover_picture As String
Dim report_cell_index As Double
Dim report_cell As String

'************************Create Dmis Report********************
CreateRpt
'**************************************************************************************
Dim CMMNUMBER As Double
Dim calcert As String
CMMNUMBER = Val(frmJobInfo.txtJobInfo(12))
If CMMNUMBER < 2 Or CMMNUMBER > 4 Then
Do
CMMNUMBER = InputBox("You have entered and incorrect CMM Machine Number!" & vbCrLf & "Please re-enter" _
, "INCORRECT CMM MACHINE ID")
Loop Until CMMNUMBER > 1 And CMMNUMBER < 5
Else
If CMMNUMBER = 2 Then calcert = "c:program filesjncmmcmm2.gif"
If CMMNUMBER = 3 Then calcert = "c:program filesjncmmcmm3.gif"
If CMMNUMBER = 4 Then calcert = "c:program filesjncmmcmm4.gif"
End If
If CMMNUMBER = 2 Then calcert = "c:program filesjncmmcmm2.gif"
If CMMNUMBER = 3 Then calcert = "c:program filesjncmmcmm3.gif"
If CMMNUMBER = 4 Then calcert = "c:program filesjncmmcmm4.gif"
frmJobInfo.txtJobInfo(12) = Str(CMMNUMBER)
'************************Create Excel Cover Sheet********************
Set objExcel = Excel.Application
Set objWB = objExcel.Workbooks.Open("c:program filesjncmm
eport_dmis.xlt")
Set objRC = objWB.Worksheets("REPORT COVER")
objRC.Range("b7").Value = frmJobInfo.txtJobInfo(0)
objRC.Range("b8").Value = frmJobInfo.txtJobInfo(1)
objRC.Range("b9").Value = frmJobInfo.txtJobInfo(2)
objRC.Range("b10").Value = frmJobInfo.txtJobInfo(3)
objRC.Range("b11").Value = frmJobInfo.txtJobInfo(4)
objRC.Range("b12").Value = frmJobInfo.txtJobInfo(5)
objRC.Range("b13").Value = frmJobInfo.txtJobInfo(6)
objRC.Range("b14").Value = frmJobInfo.txtJobInfo(7)
objRC.Range("b15").Value = frmJobInfo.txtJobInfo(8)
objRC.Range("b16").Value = frmJobInfo.txtJobInfo(9)
objRC.Range("f12").Value = frmJobInfo.txtJobInfo(10)
objRC.Range("f13").Value = frmJobInfo.txtJobInfo(11)
objRC.Range("f14").Value = frmJobInfo.txtJobInfo(12)
objRC.Range("A22", "h44").Cells.Select
cover_picture = frmJobInfo.txtJobInfo(13)
objRC.Pictures.Insert cover_picture
'**************************************************************************************
'************************Create Excel Report Sheet********************
Dim fso, r
Set fso = CreateObject("Scripting.FileSystemObject")
Set r = fso.OpenTextFile(txtRptOutput.Text, 1)
report_cell_index = 3
Set objRC = objWB.Worksheets("Report")
Do
strReadLine = r.readline
report_cell = "A" & report_cell_index
objRC.Range(report_cell).Value = strReadLine
report_cell_index = report_cell_index + 1
'r.skipline
Loop Until r.atendofstream = True
r.Close
'**************************************************************************************
'************************Create Excel Calibration Sheet********************

Set objRC = objWB.Worksheets("Calibration")
objRC.Range("A1").Value = ""
'objRC.Range("A1").Cells.Select

objRC.Pictures.Insert calcert
'**************************************************************************************
'************************Save Excel Report********************
excel_filename = Left(frmJobInfo.txtRptOutput, Len(frmJobInfo.txtRptOutput) - 4)
excel_filename = excel_filename + ".xls"
ActiveWorkbook.SaveAs FileName:=excel_filename, _
FileFormat:=xlNormal, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
objExcel.Quit
Set objExcel = Nothing
Set objWB = Nothing
Set objRC = Nothing

'**************************************************************************************
MsgBox "Reports Completed!" & vbCrLf & vbCrLf & "TextFile=" & frmJobInfo.txtRptOutput & _
vbCrLf & "Excel File=" & excel_filename, , "REPORTS COMPLETE"
frmJobInfo.txtRptInput = ""
frmJobInfo.txtRptOutput = ""
Dim x As Integer
x = 0
Do
If x = 9 Then
frmJobInfo.txtJobInfo(9) = "N/A"
x = x + 1
Else
frmJobInfo.txtJobInfo(x) = ""
x = x + 1
End If
Loop Until x = 13

End Sub

Thank you!
Rich

How To Close Excel
Hi
I like to know how to properly close excel properly after opening it as I can see excel.exe is still running behind (from task manager) and I cannot open it again unless excel.exe is ended from task manager. Pls help me.

How To Close The Excel With VB?
the following is the standard example program of operatong excel with VB.

but cann't close the excel , when we click the command5, the excel will found in the task manange.


Code:
xlsApp.Workbooks.Close
Set xlsApp = Nothing


shall close the excel , but cann't , why?

=============An entire excel example program===============


Code:
Option Explicit

Dim xlsApp As Excel.Application
Dim wrdApp As Word.Application

Private Sub Command1_Click()
Set xlsApp = Excel.Application
With xlsApp
'Show Excel
.Visible = True
'Create a new workbook
.Workbooks.Add
'Put text in to the cell that is selected
.ActiveCell.Value = "Hi"
'Put text into A3 regardless of the selected cell
.Range("A3").Value = "This is an example of connecting to Excel"
End With
End Sub

Private Sub Command2_Click()
'close the workbook
xlsApp.Workbooks.Close
'Close Excel
xlsApp.Quit
End Sub

Private Sub Command3_Click()
Set wrdApp = New Word.Application
With wrdApp
'Show Word
.Visible = True
'Create New Document
.Documents.Add
'Add text to the document
.ActiveDocument.Content.Text = "Hi"
.ActiveDocument.Content.Text = "This is a test example"
End With
End Sub

Private Sub Command4_Click()
'Close the current document
wrdApp.ActiveDocument.Close
'Close Word
wrdApp.Quit
End Sub

Private Sub Command5_click()
'Clear the memory
Set xlsApp = Nothing
Set wrdApp = Nothing
End Sub

Excel Will Not Close
Hello! I have the following code. I generate a report into an excel and the I make some modifications in the xls file. The thing is that excel will not close at the end of the process. I have attached the code. Thank you!

Close Excel From VB
When an instance of Excel is opened like this:


VB Code:
Set xlApp1 = New Excel.Application

How do you shut it down when you're done?

Norris

Close Excel Again
When I create an excel object, make my stuff, and close it remains in the taskbar.

This is to generate a report, so If I try to open it again it works fine, but just with simple values( xls.cells(1,1)=3), but I can´t use formulas or try to fit columns cause I get the error
"Object Variable or With block not set"

I've read posts asking this and of course the replies but I can't make it work

Im doing this

Dim xla As excel.Application
Dim xlb As excel.Workbook
Dim xls As excel.Worksheet

Set xla = CreateObject("Excel.application")
xla = True
Set xlb = xlb.Workbooks.Add
Set xls = xlb.Worksheets(1)

xla.Workbooks(1).Close SaveChanges:=true
Set xls = Nothing
Set xlb = Nothing

xla.Quit
Set xla = Nothing

I don't know if this can help but i have seen this:

after this lines

Set xla = CreateObject("Excel.application")
in the taskbar appears "Excel"
xla = True
then "Microsoft Excel"
Set xlb = xlb.Workbooks.Add
then "Microsoft Excel - Workbook1"

and when closing..
xla.Workbooks(1).Close SaveChanges:=true
again "Micrsoft Excel"
Set xls = Nothing
Set xlb = Nothing
the same "Microsoft Excel"
xla.Quit
in the taskbar just appears "Excel"
Set xla = Nothing
and this one don't destroy the object
and remains in the taskbar

Any ideas what to do???

I don't know what to do now.

Im using win 98 and Off 97

Close Excel
Hello, anyone know how to close all excel spreadsheets that are currently open?

Thanks

Chris

Cannot Close Excel
My code is


Code:
Public xApp As Excel.Application
Private Sub Command1_Click()
Dim wb As New Excel.Workbook, str As String
Set xApp = CreateObject("Excel.Application")
xApp.Visible = True
str = "Myfile.xls"
Set wb = xApp.Workbooks.Open(FileName:=str)

wb.Close False
End Sub

Private Sub Command2_Click()
xApp.Quit
Set xApp = Nothing
End Sub


When I click on Command2, Excel window is closed but an Excel process always appears in Window Task Manager,Process Tab. If I run above code again, two Excel processes are in Window Task Manager and so on.
Anyone can help me to terminate Excel processes?

Close Excel
IS there a way to close Excel without it giving a popup message to save information

this is what I use

xlApp.Quit

rest of code

Dim xlApp As excel.Application
Dim objWrkSht As Worksheet
Set xlApp = New excel.Application


xlApp.Workbooks.Add

Set objWrkSht = xlApp.ActiveWorkbook.Sheets(1)

Force Close All Of Excel
How can I close all of the workbooks open. My commandbutton1 saves workbook1 and then will close it and then not save workbook2 but close. Forcing excel to completely close. I use VBA. I tried application.Quit but it returns to workbook2 and stays open. Is there a magic code to shutoff excel completely?

Thank you

Excel Objects Won't Close
I have an application where I am opening an excel file (template), writing values to certain cells, then printing the report in a loop inside of a class module. At the beginning of the loop I am instantiating an excel application object, workbook object(from existing workbook), and worksheet object(active worksheet property of workbook object) in that order. After printing the report, I set the worksheet object to NOTHING, Close the workbook object (save changes=true), set the workbook object = NOTHING, then finally set the application object = NOTHING. The problem is that after several loops, I notice that active excel tasks are accumalating in the task manager up to 5 or 6, subsequently causing memory problems. when I "end task" I get the "Program not responding...." message. What am I doing wrong????

Excel Close Methods?
Edit by Moderator:
Please use the [vb][/vb] vb tags with your code


hi,

I'm wondering what methods i need in order to completely close down an excel process.

I've successfully opened excel, created a chart and saved it however I am unsure which methods to call to

close it.

Here's the initialisation code:

Code:
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
Dim xlWkb As Excel.Workbook
Set xlWkb = xlApp.Workbooks.Add
Dim xlSht As Excel.Worksheet
Set xlSht = xlWkb.Worksheets(1)
Dim xlChart As Excel.Chart
and here's the process close methods im using at the moment.

Code:
Call xlWkb.Close
Call xlApp.Quit
Set xlApp = Nothing
so, basically, what I'm wondering is should I be calling any other methods too.

After exiting my VB app I stills ee one EXCEL.EXE process in my task manager so I know I'm not closing it

down fully,

Any help much appreciated!

Please Help With This Excel Before Close Event
Hi All,

I have a big problem in my code I have an function that checks my Excel file back into a DB the problem is that the function is triggered though a button on my VB app, How can I call that function when I have closed the Excel file?
The program is attached you might have to change the this file path to where you Excel.exe is


Code:
Shell "C:Program FilesMicrosoft OfficeOFFICE11EXCEL.exe " & DiskFile, vbNormalFocus
To view a file click on a name in the list then double click an item in the listview when you close the file a button will appear asking to save the document when you click the button triggers the check back in function.

Thanks

Loftty

Close Excel Automatically
Guys,
Real simple, yet stupid question, is there a way through VBA to have Excel close itself? Please let me know. I have tried


Code:
Excel.Application.Quit

at the end of my sub and it doesn't close. Thanks for all your help!

Close Excel NOT Save
I've got a VB script problem...

I'm opening one excel sheet, activating an activeX component on that sheet which loads a string file into cells 1,1.

Then a 2nd sheet opens based on the string in 1,1 (the string contains the filename)

My problem is that when I'm shutting down the apps, the one containing the changes keeps prompting me if I want to save changes.

"object".Quit
(I get prompted here to save changes)
Set "object" = Nothing
...

How can I force the cancel or no answer into my script to prevent the pop up box from appearing??

My excel work is all behind the scenes, so this is no good.

Excel Object Will Not Close
I have my program call Excel to open take some data create a graph then save the file and close Excel. The problem is Excel will not close. The first time you use the procedure it works fine, but the next time it will error because excel is still running and if you look in the taskbar an instance of excel.exe is running.
Code:
Private Sub Command1_Click()
Dim MyXlApp As Object
Dim MyXlWB As Object

Set MyXlApp = CreateObject("Excel.Application")
Set MyXlWB = MyXlApp.Workbooks.Open(FileName:="c: est.xls")

MyXlApp.Visible = False
Application.Run ("test.xls!greg")
MyXlWB.Close
Set MyXlWB = Nothing
MyXlApp.Quit
Set MyXlApp = Nothing
end sub

Why wouldn't this work?
Once I exit the project Excel will finally close.

Thanks

Close An Excel.workbooks
I know this thread have been put and i see it the "Tutors Corners" > "Automating Excel from VB 6.0" but it doesnt help me

In my project i have to open 3 excel Workbooks and of course i must close them, so i put in my code ( the same for 3 ) :


Code:
Exc.Workbooks.Close
Exc.Quit
Set Exc = Nothing

where Exc is an Excel.application, my error came when 1 of these keep running on my computer after close my application, so i cant work with Excel, and with my application, if i Press the famous sequence ( CTRL + ALT + SUPR ), an Excel Reference are there thanks for your time.

Excel Wont Close
HI,

I have instructed the user to open Excel and them by a control I close the workbook and application. Yet with the code below it is not closing. Can someone give some help please as I cant figure out the reason why.

Code:
Private Sub Command1_Click()
On Error Resume Next

If Workbooks("Book1") Is Nothing Then
'Excel wasn't open -
MsgBox "Workbook is not open"

Else
MsgBox "Workbook is open"

Set objExcel = Nothing
Set objWorkBook = Nothing
Set objWorkSheet = Nothing

objWorkSheet.Quit
objWorkBook.Quit
objExcel.Quit
End If

Close Excel From Within Macro?
Hi
I have designed a customized login screen that is displayed in the Workbook_Open event. How do I cause the Excel spreadsheet to close if the user presses Cancel or the Close button (X button) on the login form?
I have another related question. How do I set the startup object in Excel VBA. I know there is an option while using VB, but what about VBA?
Thanks,
Sarah

How To Close A Excel Application
I hava a problem...

I am open a excel file..., but if another user have open the file i have to close it by code

how can i detect if the file is open? and if idetect it how can i close it?

Please someone help me, it's high priority for me..

Exceuse my bad english... i am from panama...and i dont know english so mush...

Bye

Close Excel After Printing.
My program creates an excel object, opens a file in it and prints, then quits the excel object.
However it quits too early and comes up with a prompt asking if it should continue printing or quit.

This problem can be solved in Word by using the following

While objWord.BackgroundPrintingStatus
DoEvents
Wend

Does anyone know if and how this can be done in Excel or another way?

Thanx.

Close/Quit Excel
Hi,
I have build an Addin in excel and it has got an update option. I have build VB application "abc.exe" which would open once user clicks on update option. This VB application can copy and paste addin from and to the appropriate folder. However it can only do it sucessfully unless all excel files are closed.

I am struggling to build a code to completely quit exel application.

I would appretiate if someone could help me out with this. It might be quite simple enough but I am newbie to VB coding hence seeking help . Any other suggestion to update/replace my addin in excel is welcome.

Thanks in advance,
Ash

Close Excel Application
i have a code to import data from excel to sql server.
it is doing well first time.
and when i try to import second time it give the following error.
and in task bar i notice that instance to excel is running.
any possibility of stopping that

Close All Excel **Resolved**
hey all,

I have two excel workbooks that I open from within vb6, they are not visible.

I am trying to close all excel workbooks, and excel itself on my main form unload event

what is the best way to do this?

thanks in advance

Excel Object Won't Close...
Hi y'all (as we say here in the UK)

Ok - I'm writing data to an excel workbook from a VB6 project, and when a large amount of data is written, the excel instance won't go away (ctrl+alt+delete shows it sitting at the bottom of the list - have to end-task it manually to get other things to happen). Can I use a bit of code to check if it's still there and end-task it if necessary?

Here's the relevant bit of code I'm using (which works fine for a smaller amount of data):

Code:
'Create new workbook, rename sheet
Set xlOut = CreateObject("Excel.Application")
With xlOut
.Application.DisplayAlerts = False
.Application.Workbooks.Add
.Range("A1").Select
'Populate Cells
CurrentRow = 0
For intLoop = 0 To RecCount
frmPrinting.lblPrinting.Caption = "Creating workbook: " & intLoop & "/" & RecCount: DoEvents
For intSubLoop = 0 To 34
If intSubLoop = 17 Or (ImpExp = "IMP" And intSubLoop = 20) Or (ImpExp = "EXP" And intSubLoop = 19) Then
.Cells(intLoop + 1, intSubLoop + 1).Formula = Format(Data(intLoop, intSubLoop), "#####")
.Cells(intLoop + 1, intSubLoop + 1).NumberFormat = "dd/mm/yy"
Else
.Cells(intLoop + 1, intSubLoop + 1).Formula = Data(intLoop, intSubLoop)
End If
Next intSubLoop
Next intLoop
.Cells.Select
.Cells.EntireColumn.AutoFit
.Range("A1").Select
'Save
SaveName = "C:Data~" & Format(Now(), "hhmmss") & Format(Now(), "ddmm") & ".xls"
.Workbooks(1).SaveAs SaveName
.Quit
End With
Set xlOut = Nothing

Excel Won&#039;t Completely Close!
Hi,

I'm having trouble completly closing Excel
I'm creating the Excel object like this:

Set appxl = CreateObject("Excel.Application")
Set xl = appxl.Application


'Then I'm killing it like this:

Set appxl = GetObject(, "EXCEL.Application")
With appxl
.ActiveWorkbook.Close savechanges:=False
.Quit
End With
Set appxl = Nothing
Set xl = Nothing

It disapears from the taskbar as if it's gone but low and behold it's still sitting as open in the task manager.
What am I doing wrong? It still closes with my application but I want it gone when I tell it to go!
Please help.

Thank You in advance.

How To Close The Instance Of Excel.
hi all,

I'm doing a application which will write some information in Excel file & save.

After saving the excel application I wrote code that

ObjExcel.quit.

But in task manager the Excel.exe is running, When I entirely close my project, it is ending.
Actually this excel is a part of the project, so I don't want to close it each & every time.

Help me how to close the instance of Excel.

Thx
Bala





Edited by - suzhibala on 9/28/2004 10:50:33 PM

Excel Can Seem To Close Application
Hi people!

I am having a lot of trouble with a project i am into. The problem is that i open a new excel application in my VB program, work with it and when i try to close, it doesn't seem to do it!!

When i run the code and try to use excel again, it gives me an error that says that the application is busy: swich to, retry, help (that message box)

Can't seem to find what im doing wrong, so pleeeeeease, somebody, HELP

I have included the parts of code where i do the excel work, let me know please.

Thanks in advance

.........

Dim xlApp As New Excel.Application
Dim xlBook As Excel.Workbook

Set xlApp = New Excel.Application

................

    'test if file selected is excel
    If Right(f_strFileName, 4) = ".xls" Then
        default = Month(Date)
        dataMonth = InputBox("Please, type in the MONTH in which the data refers to:", _
                    "TYPE MONTH", default)
        'Open a workspace
        Set xlBook = xlApp.Workbooks.Open(gf_strDataPath)
        xlApp.Visible = True
        
'***********************************************************
    'In the ActiveWorkbook
      With xlBook
        For i = 1 To xlBook.Sheets.Count 'get all the sheets
            .Sheets(i).Select 'and for each:

            'loop to see if first row is just title, if it is, just delete row to be able
            'to transport to Access properly
            Do
            blank = 0 'variable to count blank cells
            rwIndex = 1 'counting the colums
                
                For colIndex = 1 To 5 'look at first 10 columns if blank, add 1 to blank variable
                    If WorksheetFunction.IsNonText(Cells(rwIndex, colIndex)) = True Then
                         blank = blank + 1
                    End If
                Next colIndex
         
                If blank > 2 Then 'if more than 5 colms are blank, is title
                    Rows(rwIndex).Delete 'so delete it
                End If
            Loop Until blank = 0
                   
            'loop through all columns for blank cells fixing headings for proper string
            'until it finds 2 consecutive blanks were most probably data will end
            For colIndex = 1 To 250
                Cells(rwIndex, colIndex).Value = fixname(Cells(rwIndex, colIndex))
                If WorksheetFunction.IsNonText(Cells(rwIndex, colIndex)) = True Then
                    If WorksheetFunction.IsNonText(Cells(rwIndex, colIndex + 1)) = True Then
                        Exit For
                    End If
                End If
            Next colIndex
    'xlApp.DisplayAlerts=FALSE

            '*****************************
            'getting name of sheet to save it as 1 workbook file with the name of the sheet
            sxname = Sheets(i).Name
            sxname = fixname(sxname)
            sxNameEnd = "c:" & sxname & ".xls" 'saving as excel book
            .Sheets(i).Copy
   
            'if there is a file with the same name in drive, delete it
            'to be replaced with new file
            On Error Resume Next
            If FilExists(sxNameEnd) = True Then
                Debug.Print sxNameEnd
                Kill (sxNameEnd) 'call to delete file
            End If
            
            ActiveWorkbook.SaveAs FileName:=sxNameEnd
            ActiveWorkbook.Close (True)
            
            'import the current sheet saved as a wbook into the Access db
            'acApp.DoCmd.DeleteObject acTable, sxname
            Dim strTbl As String
                For j% = 0 To db.TableDefs.Count - 1
                    'Get the table name
                    strTbl = db.TableDefs(j%).Name
                     Debug.Print strTbl
                        
                    'Make sure the table names are not the Access
                    'system tables. (tables begin with MSys )
                            
                    If Left(UCase(strTbl), 4) <> ACCESS_SYSTEM_PREFIX Then
                      
                        If strTbl = sxname Then
                            Debug.Print strTbl
                            db.TableDefs.Delete (strTbl)
                            'j% = j% - 1
                        End If
                    End If
                Next j%


            acApp.DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel97, _
                                            sxname, sxNameEnd, True

            Next i 'do for all sheets in workbook
         End With
         db.Close
         
        strNewTableName = dataMonth
        strtable = txtSelect.Text
          'get calculation from library and create new table with data selected
        strSQL = "SELECT " & strtable
        strSQL = strSQL & " INTO " & strNewTableName
        strSQL = strSQL & " FROM " & txtFrom.Text
        strSQL = strSQL & " WHERE " & txtWhere.Text
            
        acApp.DoCmd.RunSQL strSQL
        strSQL = ""
        
        Dim xlpath As String
        xlpath = "c:AnalystData"
        xlWB = xlpath & strNewTableName
        'get into out to excel file
        acApp.DoCmd.OutputTo acOutputTable, strNewTableName, acFormatXLS, xlWB
        
            xlBook.Close (False)
    Set xlBook = Nothing
    
   
    xlApp.Quit

Excel Instance Does Not Close...
Greetings!

I have am trying read an Excel file using Excel Object Library 9.0 (Excel 2000).
Next, an HTML page is parsed and a new HTML page is created based on the data in the Excel file.
Below is the code snippet.

----------------------------------------

Code:Option Explicit

Dim strHTML As String
Dim objXL As New Excel.Application
Dim objWS As Excel.Worksheet
Dim objWS1 As Excel.Worksheet
Dim objWS2 As Excel.Worksheet


Private Sub cmdProcess_Click()
    ...
    ...
    ...
    
    objXL.Workbooks.Open Trim(txtPickList.Text), , True
    Set objWS = objXL.Worksheets(1)
    Set objWS1 = objXL.Worksheets.Add
    
    ...
    ...
    ...
    
    ReorderData
    
    objXL.Workbooks(1).Close 0
    Set objWS = Nothing
    Set objWS1 = Nothing
    objXL.Quit
    Set objXL = Nothing
    
    ...
    ...
    ...
    
End Sub


Private Sub ReorderData()
    ...
    ...
    ...
    
    For lRows1 = 1 To objWS1.UsedRange.End(xlDown).Row
        For Each objTable In objElements
            If InStr(objTable.innerText, "ORDER # " & objWS1.cells(lRows1, 1).Value) > 0 Or bFetch = True Then
                If iCount = 1 Then StatusMessage " Reordering... ORDER# " & objWS1.cells(lRows1, 1).Value
                strHTML = strHTML & objTable.outerHTML & "&nbsp;<br>"
                If iCount = 3 Then strHTML = strHTML & "<p align=center>----------</p>"
                iCount = iCount Mod 3 + 1
                bFetch = IIf(iCount = 1, False, True)
            End If
        Next
    Next lRows1
    
    ...
    ...
    ...
End Sub


Private Sub StatusMessage(strStatus As String)
    txtStatus.Text = txtStatus.Text & strStatus & vbCrLf
    txtStatus.SelStart = Len(txtStatus.Text)
    txtStatus.Refresh
End Sub

----------------------------------------

Now, the problem that I am facing is that the Excel instance never closes even after the code in the "cmdProcess_Click" is processed. However when the code in "ReorderData" is commented it works fine.

Another point is that, this problem arises only on Win98 and WinME. but it works fine under Win2000.

Can anyone pls help me out with this.
Thx a lot.



Have a nice day.
Warm Regards,
-Carrot

How Do I Run Or Close A Process - In Excel!
Using macro's or whatever, i'm sure ive done it before, but i just cant remember how.

How To Close An Excel Workbook?
After I copy a large section of a worksheet and paste it in a different workbook, how do I close the source workbook without it asking me if I want to save the Clipboard that contains data?

I've already pasted the data and I just want to close the workbook. I haven't modified anything. I'm opening up many workbooks in a loop, 80+, I'm running out of memory. I need to close these as I get through with them.

I'm using VB and not VBA.

Thanks in advance.

klt

I Can't Close Excel Object From VB
Hi people!

I call to excel workbook from vb app. I have change Excel workbook and now the application does't work correctly.

Is there any size limit? The workbook is opened and the data read, but app can't close the task in the server.

Any one know about that?

I use these program lines.

objExcel.ActiveWorkbook.Close (False)
objExcel.Quit
Set objExcel = Nothing


Thank a lot.
---------------------
Buenas tardes!
Tengo un problema que me está llevando días y no
consigo corregirlo. Utilizo un libro excel que tiene tal
tamaño (700 KB) que ya me da error al intentar cerrar
mediante un programa en VB o desde un navegador mediante
lenguage asp.
En cambio si lo debbugo, el error desaparece. Yo creo que
es por el tamaño y quiero alargar algún parametro que
establezca el tiempo de espera. En si no es que de ningún
mensaje de error, sino que no termina la operación y se
queda abierta la aplicación en el servidor.
Lo cierro de la siguiente manera. Alguien me podría ayudar?
¿?

objExcel.ActiveWorkbook.Close (False)
objExcel.Quit
Set objExcel = Nothing

Muchas gracias.

How To Close Excel Using Macro In Access.
I've opened an excel file and manipulated it using macros from access. I don't want it to continue running and I'm having trouble finding the code to close it. (Good ol' record macro can't record its own demise.)

Close Excel Workbook Without Saving
Anyone know the VB code to put in a macro to close an excel workbook.

I am trying

Activeworkbook.close

no luck

Excel VBA Run Macro On Workbook Close
How can I run some code when the workbook is being closed?

I would like to be able to automatically protect my sheets on workbook close, and thought something similar to Auto_Open would work, but I couldnt get Auto_Close to work?

Excel Copy Paste Close
if i have done the following....

set oExcel = CreateObject("Excel.application")
Set oWorkBook = oExcel.workbooks.add
oExcel.workbooks.open App.path + "ook1.xls"


how would i then copy the contents of book1.xls to the new excel and then close book1.xls

The Correct Way To Close An Excel File After Using?
Hi,
I'm using the below to open a existing excel file to do some work.
But I did not include a closing file command, I think will cause some problem when I try to open another new excel file, and also the selected existing file will open together with a new file "book1" too. Is there a way not to create a new excel file "book1"
I just wanna open the existing file and successfully close that file after use..
Anyone can help me?


Code:
Dim oXcel As Excel.Application
Dim oWorkBk As Excel.Workbook
Dim oWorkSht As Excel.Worksheet

Set oXcel = New Excel.Application
Set oWorkBk = oXcel.Workbooks.Add
Set oWorkSht = oWorkBk.Worksheets("Sheet1")

oXcel.Workbooks.Open ("C:Documents and SettingsadministratorDesktop170206initial-tariff.xls")
oXcel.Visible = True

Cleanup:
Set oWS = Nothing
If Not oWB Is Nothing Then oWB.Close
Set oWB = Nothing
oExcel.Quit
Set oExcel = Nothing

Copyright © 2005-08 www.BigResource.com, All rights reserved