Vba to kill excel

VBA Kill function in Excel or statement is categorized as File and Directory function. This built-in VBA Kill statement deletes a file or files based on the specified path name in Excel VBA. You can specify wildcard characters either * and ? to delete multiple files.

This function can be used in either procedure or function in a VBA editor window in Excel. We can use this VBA Kill Function in any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the Kill function, where we can use this Kill Function and real-time examples in Excel VBA.

Table of Contents:

  • Overview
  • Syntax of VBA Kill Function
  • Parameters or Arguments
  • Where we can apply or use VBA Kill Function?
  • Example 1: Delete a File
  • Example 2: Delete a File(Returns an Error)
  • Example 3: Delete all Files using Wild card Character(* and ?)
  • Example 4: Delete all .xls Files from the C-Drive
  • Example 5: Delete all .ppt Files from the Current Directory
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the Kill Function in VBA is

Kill(PathName)

The Kill Function returns doesn’t return any file. It deletes a file or files. The Path-name argument represents the file path name. If path-name doesn’t include a folder name, the specified file considers current folder.

Parameters or Arguments:

The Kill function has one argument in Excel VBA.
where
PathName:It is a mandatory string type parameter. The PathName argument represents the path of a file, folder, or directory. It helps to delete a file or files. It contains wild card characters either *(multiple characters) and ? (single Character).

Wild Card Character Description
* Allows you to match any string of any length (including zero length)
? Allows you to match on a single character

Where we can apply or use VBA Kill Function?

We can use this Kill Function in VBA MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Delete a File

Here is a simple example of the VBA Kill function. This below example deletes a file and displays message.

'Delete a File
Sub VBA_Kill_Function_Ex1()

    'Variable declaration
    Dim sPath As String
    
    sPath = "C:SomeswariVBAF1VBA FunctionsVBA Text FunctionsTemp.xlsm"
    
    Kill (sPath)
        
    MsgBox "File Deleted Successfully : " & vbCrLf & sPath, vbInformation, "VBA Kill Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA Kill Function

Example 2: Delete a File(Returns an Error)

Here is a simple example of the VBA Kill function. This below example returns an error. Because the specified is not available.

'Delete a File(Returns an Error)
Sub VBA_Kill_Function_Ex2()

    'Variable declaration
    Dim sPath As String
    
    sPath = "C:VBAF1VBA FunctionsVBA Text FunctionsTemp.xlsx"
    
    Kill (sPath)
        
    MsgBox "File has deleted : " & vbCrLf & sPath, vbInformation, "VBA Kill Function"
    
End Sub

Output: Here is the screen shot of the second example output.
VBA Kill Function

Example 3: Delete all Files using Wild card Character(* and ?)

Here is a simple example of the VBA Kill function. This below example deleted all .doc files from the ‘Temp’ folder. Here we used wild card characters(* and ?) to delete all .doc files.

'Delete all Files using Wild card Character(* and ?)
Sub VBA_Kill_Function_Ex3()

    'Variable declaration
    Dim sPath As String
    Dim iOutput As Integer
    
    sPath = "C:SomeswariVBAF1VBA FunctionsVBA Text FunctionsTemp*.doc?"
    
    Kill (sPath)
        
    MsgBox "Deleted all files from the Temp Folder: " & vbCrLf & sPath, vbInformation, "VBA Kill Function"
    
End Sub

Output: Here is the screen shot of the third example output.
VBA Kill Function

Example 4: Delete all .xls Files from the C-Drive

Here is a simple example of the VBA Kill function. This below example deleted all .xls files from the ‘C’ Drive. Here we used wild card character(*) to delete all .xls files from the C-Drive.

'Delete all .xls Files from the C-Drive
Sub VBA_Kill_Function_Ex4()

    'Variable declaration
    Dim sPath As String
    
    sPath = "C:*.xls"
    
    If Len(Dir(sPath)) > 0 Then
        SetAttr sPath, vbNormal
        Kill sPath
    End If
        
    Kill (sPath)
        
    MsgBox "Deleted all .xls files from the C-Drive: " & vbCrLf & sPath, vbInformation, "VBA Kill Function"
    
End Sub

Output: Here is the screen shot of the fourth example output.
VBA Kill Function

Example 5: Delete all .ppt Files from the Current Directory

Here is a simple example of the VBA Kill function. This below example deleted all .ppt files from the current directory. Here we used wild card character(*) to delete all .ppt files from the current directory.

'Delete all .ppt Files from the Current Directory
Sub VBA_Kill_Function_Ex5()

    'Variable declaration
    Dim sPath As String
    
    sPath = "*.ppt"
    
    If Len(Dir(sPath)) > 0 Then
        SetAttr sPath, vbNormal
        Kill sPath
    End If
    
    Kill (sPath)
        
    MsgBox "Deleted all .ppt files from the current Directory: " & vbCrLf & sPath, vbInformation, "VBA Kill Function"
    
End Sub

Output: Here is the screen shot of the fifth example output.
VBA Kill Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Удаление любых файлов из кода VBA Excel с помощью оператора Kill и метода DeleteFile объекта FileSystemObject. Знаки подстановки, синтаксис, примеры.

Оператор Kill

Описание

Kill – это оператор, предназначенный для удаления файлов с диска.

Синтаксис

  • PathName – это строковое выражение, задающее одно или несколько имен файлов (по шаблону), которые требуется удалить.

Строка PathName может содержать каталоги (папки) и букву диска. Если файл с именем PathName не существует, будет сгенерирована ошибка.

Оператор Kill поддерживает использование знаков подстановки в последнем компоненте параметра PathName (собственное имя файла без пути к нему):

  • Звездочка (*) – заменяет любое количество символов или ни одного.
  • Вопросительный знак (?) – заменяет один символ или ни одного.

Знаки подстановки позволяют создать шаблон, по которому можно удалить сразу несколько файлов.

Примеры

Пример 1
Удаление одного файла без проверки его существования (в примере — удаление книги Excel):

Sub Primer1()

  On Error Resume Next

  Kill ThisWorkbook.Path & «Книга1.xlsx»

End Sub

Инструкция On Error Resume Next нужна для того, чтобы корректно завершить программу в том случае, если файла с именем PathName не существует.

Пример 2
Удаление одного файла с проверкой его существования:

Sub Primer2()

Dim myPathName As String

  myPathName = «C:Новая папкаФайл1.docx»

  If Dir(myPathName) <> «» Then Kill myPathName

End Sub

Пример 3
Удаление нескольких файлов по шаблону:

Sub Primer3()

  On Error Resume Next

  Kill «C:Новая папкаСправка*»

End Sub

В результате работы этого кода VBA Excel будут удалены все файлы с любыми расширениями, которые начинаются со слова «Справка». Если строку Kill "C:Новая папкаСправка*" заменить строкой Kill "C:Новая папка*2020*", она удалит все файлы, в имени которых есть подстрока «2020».

Как удалить объект ThisWorkbook с помощью оператора Kill из кода VBA Excel, размещенного в нем же, смотрите в статье: Удаление книги из собственного кода.

Метод DeleteFile

Описание

DeleteFile – это метод объекта FileSystemObject, предназначенный для удаления файлов с диска из кода VBA Excel.

Синтаксис

Object.DeleteFile PathName, [force]

  • Object – переменная, возвращающая объект FileSystemObject (обязательный параметр);
  • PathName – строковое выражение, задающее одно или несколько имен файлов (по шаблону), которые требуется удалить (обязательный параметр);
  • force – значение типа Boolean: True – удаляются все файлы, False (по умолчанию) – не удаляются файлы с атрибутом «только для чтения» (необязательный параметр).

В последнем компоненте параметра PathName (собственное имя файла без пути к нему) можно использовать знаки подстановки, также, как и для оператора Kill. Если указанный файл не существует, будет сгенерирована ошибка.

Примеры

Пример 4
Удаление одного файла с проверкой его существования:

Sub Primer4()

Dim fso As Object

‘Присваиваем переменной fso ссылку на новый экземпляр FileSystemObject

Set fso = CreateObject(«Scripting.FileSystemObject»)

‘Проверяем существование удаляемого файла

  If Dir(ThisWorkbook.Path & «Изображение.png») <> «» Then

    ‘Удаляем файл, если он существует

    fso.DeleteFile ThisWorkbook.Path & «Изображение.png»

  End If

End Sub

Пример 5
Удаление нескольких или всех файлов по шаблону:

Sub Primer5()

Dim fso As Object

‘Присваиваем переменной fso ссылку на новый экземпляр FileSystemObject

Set fso = CreateObject(«Scripting.FileSystemObject»)

‘Завершаем программу, если не существует ни одного файла, подходящего под указанный шаблон

On Error Resume Next

‘Удаляем указанный файл (файлы)

fso.DeleteFile «C:Новая папка*.docx»

End Sub

В результате работы этого кода VBA Excel из папки «Новая папка» будут удалены все файлы с расширением .docx.


Фразы для контекстного поиска: удаление файла, удаление всех файлов, удаление нескольких книг, удаление всех книг, удаление по шаблону.


I have used the following without success. The active workbook closes, indeed, but the excel window remains open.

Application.ActiveWindow.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False

Which is the command that terminates the application?

EDIT

To say a little more: In the workbook Open event I run a macro. I want to terminate the application when that macro finishes. I also tried this without success.

Private Sub Workbook_Open()
   Macro_MyJob
   Application.Quit
End Sub

Where should I put this Application.Quit command?

asked Sep 2, 2010 at 14:45

Brani's user avatar

BraniBrani

6,57415 gold badges46 silver badges49 bronze badges

I think your problem is that it’s closing the document that calls the macro before sending the command to quit the application.

Your solution in that case is to not send a command to close the workbook. Instead, you could set the «Saved» state of the workbook to true, which would circumvent any messages about closing an unsaved book. Note: this does not save the workbook; it just makes it look like it’s saved.

ThisWorkbook.Saved = True

and then, right after

Application.Quit

answered Sep 2, 2010 at 16:00

variant's user avatar

variantvariant

1,3442 gold badges11 silver badges18 bronze badges

To avoid the Save prompt message, you have to insert those lines

Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True

After saving your work, you need to use this line to quit the Excel application

Application.Quit

Don’t just simply put those line in Private Sub Workbook_Open() unless you got do a correct condition checking, else you may spoil your excel file.

For safety purpose, please create a module to run it. The following are the codes that i put:

Sub testSave()
Application.DisplayAlerts = False
ThisWorkbook.Save
Application.DisplayAlerts = True
Application.Quit
End Sub

Hope it help you solve the problem.

answered Apr 29, 2013 at 8:14

Leng Keong's user avatar

Leng KeongLeng Keong

1431 silver badge3 bronze badges

1

Sub TestSave()
Application.Quit
ThisWorkBook.Close SaveChanges = False
End Sub

This seems to work for me, Even though looks like am quitting app before saving, but it saves…

answered Jan 6, 2015 at 8:33

kc kalama's user avatar

kc kalamakc kalama

711 silver badge1 bronze badge

2

Application.Quit 

Should do the trick.

answered Sep 2, 2010 at 14:47

Michael's user avatar

MichaelMichael

1,6362 gold badges16 silver badges21 bronze badges

0

I tried a certain sequence that seems to work as you can see below:

ThisWorkbook.Saved = True
Application.Quit
Application.ActiveWindow.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False

ForceMagic's user avatar

ForceMagic

6,15212 gold badges68 silver badges88 bronze badges

answered Jul 17, 2013 at 19:55

Dan's user avatar

You can try out

ThisWorkbook.Save
ThisWorkbook.Saved = True
Application.Quit

answered Mar 27, 2019 at 5:19

K10's user avatar

In my case, I needed to close just one excel window and not the entire application, so, I needed to tell which exact window to close, without saving it.

The following lines work just fine:

Sub test_t()
  Windows("yourfilename.xlsx").Activate
  ActiveWorkbook.Close SaveChanges:=False
End Sub

answered Jun 7, 2018 at 13:55

Panagiotis Chatzikonstantis's user avatar

Sub button2_click()
'
' Button2_Click Macro
'
' Keyboard Shortcut: Ctrl+Shift+Q
'
    ActiveSheet.Shapes("Button 2").Select
    Selection.Characters.Text = "Logout"
    ActiveSheet.Shapes("Button 2").Select
    Selection.OnAction = "Button2_Click"
    ActiveWorkbook.Saved = True
    ActiveWorkbook.Save
    Application.Quit
End Sub

LuigiEdlCarno's user avatar

answered Jul 26, 2013 at 7:07

Menon's user avatar

Wednesday, May 06, 2009

Kill Residual Excel Process using VBA

Here is a simple VBA code to «Kill» the Excel process using VBA

Sub Kill_Excel()

Dim sKillExcel As String

sKillExcel = «TASKKILL /F /IM Excel.exe»
Shell sKillExcel, vbHide

End Sub

StumbleUpon

Related Posts Plugin for WordPress, Blogger...

  • #1

Hi again,

I have the following code to stop Excel processes running

Rich (BB code):

Sub Kill_Excel()

Dim sKillExcel As String

sKillExcel = "TASKKILL /F /IM Excel.exe"
Shell sKillExcel, vbHide

End Sub

But this also closes the main workbook. Is there a way to stop that from happening, as I only want to close those processes left trailing from the CreateObject method I use in my code.

Select all contiguous cells

Pressing Ctrl+* (asterisk) will select the «current region» — all contiguous cells in all directions.

  • #2

Rather than kill the entire Excel process, would it not be better to set the old instances of objects to nothing?

e.g.
Set MyObj = Nothing

change MyObj to the object you are trying to close.

Andrew

  • #3

The topic offers useful solution to end Excel processing in VBA.

Following demo code is I copied from that thread for Excel processing issue.

Code:

Option Explicit  Private Sub Application_Startup() Dim xlApp As Excel.Application Dim myWB As Excel.Workbook Dim myDate As Date Dim myPrompt As Variant      myDate = Date      Set xlApp = CreateObject("Excel.Application")      xlApp.Visible = False      Set myWB = xlApp.Workbooks.Open("C:UsersJThomps2DesktopClosingDays.xls")      myPrompt = xlApp.VLookup(CDbl(myDate), myWB.Worksheets("Sheet1").Range("A:B"), 2, False)         If Not IsError(myPrompt) Then         MsgBox ("Closing Day " & myPrompt)     End If          myWB.Close False        Set myWB = Nothing      xlApp.Quit      Set xlApp = Nothing  End Sub

http://www.mrexcel.com/forum/excel-questions/735062-excel-process-not-closing.html

Last edited: Feb 10, 2014

  • #4

Andrew’s solution worked great:) The reason I kept having trailing processes was because I forgot to do it to every workbook I opened.

Home / VBA / VBA Delete Workbook (Excel File)

To delete an Excel file from a folder you can use two different methods. The first method is the “Kill” statement which takes the file path to refer to the file that you wish to delete. The second method is the FileSystemObject object which has a method associated with it to delete a file.

To use these codes, go to the VBE (Code Editor) from the developer tab.

Delete a File using VBA (Kill Function)

Kill function helps you to delete a single file or multiple files, and use wildcard characters to delete more than one file. Below is the one-line code that deletes the file from the folder that I have on the desktop.

Kill "C:UsersDellDesktopSample Datafile-one.xlsx"

This code will show you an error if the workbook that you specified to delete doesn’t exist.

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Delete All the Files from a Folder using VBA

And if you want to delete all the files that you have in a folder, you can use a wildcard character.

Kill "C:UsersDellDesktopSample Data*.xl*"

Delete a File using the FileSystemObject (Object)

The file system object provides you with access to the computer’s file system. You can learn about it from here, but now, let’s write a code to remove a file.

Full Code

Sub vba_delete_file()
Dim FSO
Dim myFile As String
Set FSO = CreateObject("Scripting.FileSystemObject")
myFile = "C:UsersDellDesktopSample Datafile1.xlsx"
FSO.DeleteFile myFile, True
End Sub

Let’s say you need to write a code that can check for a file, (exists or not) and then delete it. Here’s the code that you need.

Sub vba_delete_file()
Dim FSO
Dim myFile As String
Set FSO = CreateObject("Scripting.FileSystemObject")
myFile = "C:UsersDellDesktopSample Datafile1.xlsx"
If FSO.FileExists(myFile) Then
    FSO.DeleteFile myFile, True
    MsgBox "Deleted"   
Else
    MsgBox "There's no workbook with this name."   
End If   
End Sub

More on VBA Workbooks

VBA Save Workbook | VBA Close Workbook | VBA ThisWorkbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)

  • VBA Workbook

  • Remove From My Forums
  • Question

  • Hi, I’m coding on Access VBA, and I have to open a workbook and change some data, the issue is when I close and save the workbook the excel process remains on task manager. How can I kill this process?

    Here is the code for your review:

    Sub PDW(ByVal SRCS As String)
        
        Dim objExcelApp As Excel.Application
        Dim wb As Object
        Dim ws As Worksheet
        
        Set objExcelApp = New Excel.Application
        
        Set wb = objExcelApp.Workbooks.Open(SRCS)
        
        Set ws = wb.Sheets(1)
    
       ws.Range("A1").Select
       ws.Range(Selection, Selection.End(xlDown)).Select
       
       Dim a As Integer
       a = ws.Application.Selection.Count
       
       ws.Range("F1:I" & a).Select
       
       ws.Application.Selection.UnMerge
    
       ws.Range("F1:I" & a).Select
       ws.Range("F1:I" & a).AutoFilter Field:=10, Criteria1:="1"
       ws.Application.Selection.SpecialCells(xlCellTypeVisible).Select
       ws.Application.Selection.Replace What:="", Replacement:="NA", _
           LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
           SearchFormat:=False, ReplaceFormat:=False
       
       ws.Activate
       ws.ShowAllData
    
       ws.Range("F1:I" & a).Select
       ws.Application.Selection.SpecialCells(xlCellTypeBlanks).Select
       
       ws.Application.Selection.FormulaR1C1 = "=R[-1]C"
       ws.Range("F1:I" & a).Select
       
       ws.Application.Selection.Copy
       ws.Application.Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
           :=False, Transpose:=False
       
       ws.Range("B1:C" & a).Select
       
       ws.Application.Selection.UnMerge
    
       ws.Range("B1:C" & a).Select
       ws.Application.Selection.AutoFilter Field:=10, Criteria1:="1"
       ws.Application.Selection.SpecialCells(xlCellTypeVisible).Select
       ws.Application.Selection.Replace What:="", Replacement:="NA", _
           LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
           SearchFormat:=False, ReplaceFormat:=False
           
       ws.Activate
       ws.ShowAllData
       
       ws.Range("B1:C" & a).Select
       
       ws.Application.Selection.SpecialCells(xlCellTypeBlanks).Select
       
       ws.Application.Selection.FormulaR1C1 = "=R[-1]C"
       
       ws.Range("B1:C" & a).Select
       
       ws.Application.Selection.Copy
       ws.Application.Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
           :=False, Transpose:=False
     
        If Len(Dir("c:TEMP", vbDirectory)) = 0 Then
            MkDir "c:TEMP"
        End If
        
        wb.SaveAs FileName:= _
            "C:TEMPIMP.xlsx", FileFormat:= _
            xlOpenXMLWorkbook, CreateBackup:=False
    
        wb.Close False
        objExcelApp.Quit
        
        a = Nothing
        Set ws = Nothing
        DoEvents
        Set wb = Nothing
        DoEvents
        Set objExcelApp = Nothing
        DoEvents
        
    End Sub

    Thank you.

Answers

  • This behavior generally occurs when you refer to Excel objects without referencing them via their parent objects.  In your code, I see at least one place where you’ve done this; this line:

         ws.Range(Selection,
    Selection.End(xlDown)).Select

    «Selection» is not qualified.  There may be other places where this happens, too, but I didn’t see one in a quick scan over the code.


    Dirk Goldgar, MS Access MVP
    Access tips: www.datagnostics.com/tips.html

    • Marked as answer by

      Monday, March 10, 2014 9:33 PM

  • Remove From My Forums
  • Вопрос

  • Hi,

    In my VBA proc I start by creating a VBA Excel Application:

    Set XLApp = CreateObject(«Excel.Application»)

    then…

    I finish the proc with the three rows:

    XLApp.Quit                                          
    Set XLApp = Nothing
    End Sub

    But in the Windows Task Manager, I still have a Microsoft Excel
    process which is still running.

    How to ‘kill’ this Excel process ?

    Thanks

Ответы

  • WLID1966,

    When I write Project based macros that interface with Excel I normally use the following set of statements.

    On Error Resume Next
    Set xl = GetObject(, «Excel.application»)
    If Err <> 0 Then
        On Error GoTo 0
        Set xl = CreateObject(«Excel.Application»)
        If Err <> 0 Then
            FilterApply Name:=»all tasks»
            Set xl = Nothing
            On Error GoTo 0      ‘clear error function
            Exit Sub
        End If
    End If
    On Error GoTo 0
    xl.Workbooks.Add

    And at the end of the macro I include statements similar to those you use

    xl.Quit
    Set xl = Nothing

    I just tried a test run using both the GetObject Method and the CreateObject Functions and in both cases Excel was totally removed from the Task Manager list of running applications.

    Is it possible you actually have Excel open in the background before you run your macro and that’s the instance you still see after running your macro?

    John

    • Помечено в качестве ответа

      20 марта 2019 г. 11:23

Модераторы: Ramzes, Sebas

asn
Новичок
Новичок
 
Сообщения: 34
Зарегистрирован: 29.08.2005 (Пн) 8:18

Как убить процесс Excel

Создаю объект Excel следующим образом:

ObjXlc = CreateObject(«Excel.Application»)

ObjXlc.Application.Workbooks.Open(Path)

Далее активирую нужную страницу,вставляю данные, сохраняю.

А вот убить процесс не получается. Пробовал

ObjXlc.close()

ObjXlc.quit()

ObjXlc=nothing

Excel продолжает висеть в процессах и умирает только когда закрываеш программу.

Что деляю не так?


Nord777
Гуру
Гуру
Аватара пользователя

 
Сообщения: 1144
Зарегистрирован: 22.02.2004 (Вс) 13:15
Откуда: Подольск

Сообщение Nord777 » 16.10.2006 (Пн) 19:19

у меня пашет

Код: Выделить всё
Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook

xlApp = CreateObject("Excel.Application")
xlBook = xlApp.Workbooks.Add()
xlBook.Windows(1).Caption = "Tra-ta-ta"

'Make Excel visible
xlApp.Visible = True

Threading.Thread.Sleep(3000)
xlApp.Quit()

Microsoft Visual Studio 2008

Microsoft .NET Framework 3.5


asn
Новичок
Новичок
 
Сообщения: 34
Зарегистрирован: 29.08.2005 (Пн) 8:18

Сообщение asn » 17.10.2006 (Вт) 9:32

Непрокатывает.

В процессах Excel все равно остается и уходит только после закрытия программы.


Ramzes
Скромный человек
Скромный человек
Аватара пользователя

 
Сообщения: 5004
Зарегистрирован: 12.04.2003 (Сб) 11:59
Откуда: Из гробницы :)
  • Сайт
  • ICQ

Сообщение Ramzes » 17.10.2006 (Вт) 10:12

process.kill


ANDLL
Великий гастроном
Великий гастроном
Аватара пользователя

 
Сообщения: 3450
Зарегистрирован: 29.06.2003 (Вс) 18:55
  • ICQ

Сообщение ANDLL » 17.10.2006 (Вт) 10:13

xlApp.Quit(false)

Гастрономия — наука о пище, о ее приготовлении, употреблении, переварении и испражнении.
Блог


asn
Новичок
Новичок
 
Сообщения: 34
Зарегистрирован: 29.08.2005 (Пн) 8:18

Сообщение asn » 17.10.2006 (Вт) 13:27

xlApp.Quit(false)

А это как?


ANDLL
Великий гастроном
Великий гастроном
Аватара пользователя

 
Сообщения: 3450
Зарегистрирован: 29.06.2003 (Вс) 18:55
  • ICQ

Сообщение ANDLL » 17.10.2006 (Вт) 13:32

вместо xlApp.Quit()

Гастрономия — наука о пище, о ее приготовлении, употреблении, переварении и испражнении.
Блог


asn
Новичок
Новичок
 
Сообщения: 34
Зарегистрирован: 29.08.2005 (Пн) 8:18

Сообщение asn » 21.10.2006 (Сб) 11:23

xlApp.Quit(false)

Чего-то не получается, подчеркивает (False) как ошибку.


Nord777
Гуру
Гуру
Аватара пользователя

 
Сообщения: 1144
Зарегистрирован: 22.02.2004 (Вс) 13:15
Откуда: Подольск

Сообщение Nord777 » 21.10.2006 (Сб) 16:43

так прокатывает

Код: Выделить всё
Dim xlApp As Excel.Application

Dim xlBook As Excel.Workbook

xlApp = CreateObject("Excel.Application")

xlBook = xlApp.Workbooks.Add()

xlBook.Windows(1).Caption = "Tra-ta-ta"

'Make Excel visible

xlApp.Visible = True

Threading.Thread.Sleep(3000)

xlApp.Quit()

xlApp = Nothing

xlBook = Nothing

GC.Collect()

GC.WaitForPendingFinalizers()

GC.Collect()

Microsoft Visual Studio 2008

Microsoft .NET Framework 3.5


Ramzes
Скромный человек
Скромный человек
Аватара пользователя

 
Сообщения: 5004
Зарегистрирован: 12.04.2003 (Сб) 11:59
Откуда: Из гробницы :)
  • Сайт
  • ICQ

Сообщение Ramzes » 23.10.2006 (Пн) 11:38

Совсем забыл, я когда-то то-же спрашивал, г-н Sebas послал меня в сторону System.Reflection. Помниться мне это помогло :!:


Sebas
Неуловимый Джо
Неуловимый Джо
Аватара пользователя

 
Сообщения: 3626
Зарегистрирован: 12.02.2002 (Вт) 17:25
Откуда: столько наглости такие вопросы задавать
  • ICQ

Сообщение Sebas » 23.10.2006 (Пн) 14:10

Код: Выделить всё
        Dim e As Object = Nothing 'Excel.Application
        Dim b As Object = Nothing 'Excel.Workbook
        Dim s As Object = Nothing 'Excel.Worksheet

            e = CreateObject("Excel.Application") 'New Excel.Application
            b = e.Workbooks.Add
            s = b.Worksheets(1)

            b.Close()
            e.Quit()

        If s IsNot Nothing Then
            System.Runtime.InteropServices.Marshal.ReleaseComObject(s)
        End If
        If b IsNot Nothing Then
            System.Runtime.InteropServices.Marshal.ReleaseComObject(b)
        End If
        If e IsNot Nothing Then
            System.Runtime.InteropServices.Marshal.ReleaseComObject(e)
        End If

— Я никогда не понимал, почему они приходят ко мне чтобы умирать?

sebas<-@->mail.ru


asn
Новичок
Новичок
 
Сообщения: 34
Зарегистрирован: 29.08.2005 (Пн) 8:18

Сообщение asn » 31.10.2006 (Вт) 17:00

Спасибо всем, надавали советов просто кучу. Долгими усилиями вроде получилось.


asharky
Продвинутый пользователь
Продвинутый пользователь
Аватара пользователя

 
Сообщения: 162
Зарегистрирован: 22.06.2004 (Вт) 0:39
Откуда: Батоны-ларьки-поребрики…

Сообщение asharky » 05.10.2007 (Пт) 23:03

Какая-то ерунда у меня :(

Код: Выделить всё
Module MyModule

   Sub main()

      'Dim th As Threading.Thread

      'th = New Threading.Thread(AddressOf startExcel)

      'th.IsBackground = True

      'th.Start()

      'th.Join()

      'th = Nothing

      Dim cE As New sExcel

      cE.start()

      cE = Nothing

      Console.WriteLine("Останов")

      'GC.Collect()

      'GC.WaitForPendingFinalizers()

      'GC.Collect()

      Stop

   End Sub

   Sub startExcel()

      Dim e As Object = Nothing 'Excel.Application

      Dim b As Object = Nothing 'Excel.Workbook

      Dim s As Object = Nothing 'Excel.Worksheet

      e = CreateObject("Excel.Application") 'New Excel.Application

      b = e.Workbooks.Add

      s = b.Worksheets(1)

      b.Close()

      e.Quit()

      'If s IsNot Nothing Then

      '   System.Runtime.InteropServices.Marshal.ReleaseComObject(s)

      'End If

      'If b IsNot Nothing Then

      '   System.Runtime.InteropServices.Marshal.ReleaseComObject(b)

      'End If

      'If e IsNot Nothing Then

      '   System.Runtime.InteropServices.Marshal.ReleaseComObject(e)

      'End If

   End Sub

   Class sExcel

      Implements IDisposable

      Private e As Object = Nothing 'Excel.Application

      Private b As Object = Nothing 'Excel.Workbook

      Private s As Object = Nothing 'Excel.Worksheet

      '''<summary>Процедура уничтожения экземпляра класса</summary>

      Private Sub Dispose() Implements IDisposable.Dispose

         Me.Dispose()

         If s IsNot Nothing Then

            System.Runtime.InteropServices.Marshal.ReleaseComObject(s)

         End If

         If b IsNot Nothing Then

            System.Runtime.InteropServices.Marshal.ReleaseComObject(b)

         End If

         If e IsNot Nothing Then

            System.Runtime.InteropServices.Marshal.ReleaseComObject(e)

         End If

      End Sub   ' End Dispose()

      Sub start()

         e = CreateObject("Excel.Application") 'New Excel.Application

         b = e.Workbooks.Add

         s = b.Worksheets(1)

         b.Close()

         e.Quit()

      End Sub

   End Class

End Module

Всяко-разно пытался, и через поток в т.ч., но на Stop в Main(), если не использовать GC, процесс EXCEL.EXE всё ещё висит в памяти. Исчезает только после полного завершения программы. (Не компилил! В отладочном режиме!)

Что я сделал не так? Что не понимаю? Талмуды читал тут: http://www.microsoft.com/Rus/Msdn/publish/articles/MenuButton.mspx

В культурной столице проститутки берут книгами…


Viper
Артефакт VBStreets
Артефакт VBStreets
Аватара пользователя

 
Сообщения: 4394
Зарегистрирован: 12.04.2005 (Вт) 17:50
Откуда: Н.Новгород
  • ICQ

Сообщение Viper » 06.10.2007 (Сб) 6:11

Ндя… код весьма странен… Почто такие извращения? Цель всего этого какая?

Весь мир матрица, а мы в нем потоки байтов!


asharky
Продвинутый пользователь
Продвинутый пользователь
Аватара пользователя

 
Сообщения: 162
Зарегистрирован: 22.06.2004 (Вт) 0:39
Откуда: Батоны-ларьки-поребрики…

Сообщение asharky » 06.10.2007 (Сб) 8:02

Viper писал(а):Ндя… код весьма странен… Почто такие извращения? Цель всего этого какая?

Код тестовый — не для работы, понятное дело. Задача: загрузить EXCEL.EXE и попытаться его корректно выгрузить, не выходя из программы и не привлекая GC. Но не получается :( Процесс EXCEL.EXE в памяти остается на не определенное время, если не привлекать GC.

На самом деле у меня несколько другая задача решается: прицепить вот это http://www.sls.ru/products/net/activesklad.html под .VB.NET. Но там ещё хуже всё. Разработчики вообще под .NET не работают и помочь ниче не могут. Ну а с EXCEL я вожусь чтобы разобраться с взаимодействием между .NET и COM.

В культурной столице проститутки берут книгами…


lord0n
Постоялец
Постоялец
Аватара пользователя

 
Сообщения: 845
Зарегистрирован: 30.06.2005 (Чт) 9:55
Откуда: Moskow
  • ICQ

Сообщение lord0n » 07.10.2007 (Вс) 10:17

я в свое время писал специальную процедуру для убийства ком объекта (не экселя, но тоже очень похож)

вот код:

Код: Выделить всё


   ''' <summary>

   ''' Ищет процесс Сапериона порожденный этой библиотекой и если находит, то убивает его

   ''' </summary>

   ''' <remarks></remarks>

   Private Sub KillApp()

      Dim Proc As Process() = Process.GetProcessesByName("ARCHIE32")

      Dim x As Integer

      If Not Proc Is Nothing Then

         For x = 0 To Proc.Length - 1

            If Proc(x).MainWindowTitle = "" Then 'в моем случае если заголовок окна был пустым, то процесс порождала моя программа

               Proc(x).Kill()

            End If

         Next

      End If

   End Sub

Теория — это когда что-то не работает и известно почему.

Практика — это когда что-то работает, но неизвестно почему.

Нам удалось совместить теорию с практикой, теперь ничего не работает и неизвестно почему.


asharky
Продвинутый пользователь
Продвинутый пользователь
Аватара пользователя

 
Сообщения: 162
Зарегистрирован: 22.06.2004 (Вт) 0:39
Откуда: Батоны-ларьки-поребрики…

Сообщение asharky » 07.10.2007 (Вс) 10:31

lord0n писал(а):я в свое время писал специальную процедуру для убийства ком объекта (не экселя, но тоже очень похож)

Спасибо.

Но это просто кошмар какой-то получается :( Неужели средствами .NET вообще ничего поделать не возможно? :?

Но ведь при полном окончании программы GC как-то чистит всё помеченное? Как бы это сделать не выходя из программы? Ну в самом деле: не батники же писать в планировщике? :)

Эх Билли, Билли :roll:

В культурной столице проститутки берут книгами…


lord0n
Постоялец
Постоялец
Аватара пользователя

 
Сообщения: 845
Зарегистрирован: 30.06.2005 (Чт) 9:55
Откуда: Moskow
  • ICQ

Сообщение lord0n » 07.10.2007 (Вс) 11:10

Ну я так понимаю чтобы нормально завершался процесс нужно использовать не CreateObject, а ком интерапт или раннее связывание.

Я его правда не разу не использовал: очень уж длинные команды получаются по сравнению CreateObject

вот так принудительно вызвать сборщик мусора:

я вызываю его когда завершаю работу приложения, хотя говорят что принудительный вызов GC плохой тон.

Код: Выделить всё


   Public Overloads Sub Dispose()

      KillApp() 'грохаем саперион (это предыдущая функция для убийства ком объекта)

      App = Nothing 'чистим переменные

      Doc = Nothing

      MySap = Nothing

      ' Инициировать очистку.

      ' Здесь наши объекты только помечаются

      ' как «свободные», а память не

      ' освобождается.

      GC.Collect()

      ' Подождать, пока отработают все

      ' деструкторы

      GC.WaitForPendingFinalizers()

      ' Еще раз запустить очистку – теперь

      ' память под наши объекты будет реально

      ' освобождена.

      GC.Collect()

      MyBase.Finalize()

   End Sub

Теория — это когда что-то не работает и известно почему.

Практика — это когда что-то работает, но неизвестно почему.

Нам удалось совместить теорию с практикой, теперь ничего не работает и неизвестно почему.


asharky
Продвинутый пользователь
Продвинутый пользователь
Аватара пользователя

 
Сообщения: 162
Зарегистрирован: 22.06.2004 (Вт) 0:39
Откуда: Батоны-ларьки-поребрики…

Сообщение asharky » 07.10.2007 (Вс) 11:29

lord0n писал(а):Ну я так понимаю чтобы нормально завершался процесс нужно использовать не CreateObject, а ком интерапт или раннее связывание. Я его правда не разу не использовал: очень уж длинные команды получаются по сравнению CreateObject

Всяко-разно пытался. Толку нет: пока программа не закроется, процесс висит в памяти.

lord0n писал(а):вот так принудительно вызвать сборщик мусора:
я вызываю его когда завершаю работу приложения, хотя говорят что принудительный вызов GC плохой тон.

Код: Выделить всё
   Public Overloads Sub Dispose()
      KillApp() 'грохаем саперион (это предыдущая функция для убийства ком объекта)

      App = Nothing 'чистим переменные
      Doc = Nothing
      MySap = Nothing
      ' Инициировать очистку.
      ' Здесь наши объекты только помечаются
      ' как «свободные», а память не
      ' освобождается.
      GC.Collect()
      ' Подождать, пока отработают все
      ' деструкторы
      GC.WaitForPendingFinalizers()
      ' Еще раз запустить очистку – теперь
      ' память под наши объекты будет реально
      ' освобождена.
      GC.Collect()
      MyBase.Finalize()
   End Sub

У меня в моём коде (выше) есть закоментированный:

Код: Выделить всё
                'If s IsNot Nothing Then

                '       System.Runtime.InteropServices.Marshal.ReleaseComObject(s)

                'End If

                'If b IsNot Nothing Then

                '       System.Runtime.InteropServices.Marshal.ReleaseComObject(b)

                'End If

                'If e IsNot Nothing Then

                '       System.Runtime.InteropServices.Marshal.ReleaseComObject(e)

                'End If

Из этого можно предположить, что я GC тоже пытался использовать. Нет результата всё равно.

В культурной столице проститутки берут книгами…


lord0n
Постоялец
Постоялец
Аватара пользователя

 
Сообщения: 845
Зарегистрирован: 30.06.2005 (Чт) 9:55
Откуда: Moskow
  • ICQ

Сообщение lord0n » 08.10.2007 (Пн) 15:52

а тебе так критично чтобы ексель убивался во время выполнения программы?

Теория — это когда что-то не работает и известно почему.

Практика — это когда что-то работает, но неизвестно почему.

Нам удалось совместить теорию с практикой, теперь ничего не работает и неизвестно почему.


Sebas
Неуловимый Джо
Неуловимый Джо
Аватара пользователя

 
Сообщения: 3626
Зарегистрирован: 12.02.2002 (Вт) 17:25
Откуда: столько наглости такие вопросы задавать
  • ICQ

Сообщение Sebas » 08.10.2007 (Пн) 16:17

asharky

Так у Тебя класс не диспозится))))

— Я никогда не понимал, почему они приходят ко мне чтобы умирать?

sebas<-@->mail.ru


RayShade
Scarmarked
Scarmarked
Аватара пользователя

 
Сообщения: 5511
Зарегистрирован: 02.12.2002 (Пн) 17:11
Откуда: Russia, Saint-Petersburg
  • Сайт
  • ICQ

Сообщение RayShade » 08.10.2007 (Пн) 17:23

They killed Excel! Bastards! :lol:

I don’t understand. Sorry.


asharky
Продвинутый пользователь
Продвинутый пользователь
Аватара пользователя

 
Сообщения: 162
Зарегистрирован: 22.06.2004 (Вт) 0:39
Откуда: Батоны-ларьки-поребрики…

Сообщение asharky » 08.10.2007 (Пн) 17:42

Sebas писал(а):asharky

Так у Тебя класс не диспозится))))

MyClass.Dispose() не вызван, в смысле?

Вот переделал:

Код: Выделить всё
Module MyModule

Sub main()

   For i As Integer = 1 To 10

      Dim cE1 As New sExcel

      cE1.start()

      cE1 = Nothing

      Dim cE2 As New sExcel

      cE2.start()

      cE2 = Nothing

      Dim cE3 As New sExcel

      cE3.start()

      cE3 = Nothing

      Dim cE4 As New sExcel

      cE4.start()

      cE4 = Nothing

      Dim cE5 As New sExcel

      cE5.start()

      cE5 = Nothing

      Console.WriteLine("Цикл № " & i.ToString)

      GC.Collect()

      GC.WaitForPendingFinalizers()

      GC.Collect()

   Next

   Stop

End Sub

Sub startExcel()

   Dim e As Object = Nothing 'Excel.Application

   Dim b As Object = Nothing 'Excel.Workbook

   Dim s As Object = Nothing 'Excel.Worksheet

   e = CreateObject("Excel.Application") 'New Excel.Application

   b = e.Workbooks.Add

   s = b.Worksheets(1)

   b.Close()

   e.Quit()

End Sub

Class sExcel

   Implements IDisposable

   Private e As Object = Nothing 'Excel.Application

   Private b As Object = Nothing 'Excel.Workbook

   Private s As Object = Nothing 'Excel.Worksheet

   '''<summary>Процедура уничтожения экземпляра класса</summary>

   Private Sub Dispose() Implements IDisposable.Dispose

      If s IsNot Nothing Then

         System.Runtime.InteropServices.Marshal.ReleaseComObject(s)

      End If

      If b IsNot Nothing Then

         System.Runtime.InteropServices.Marshal.ReleaseComObject(b)

      End If

      If e IsNot Nothing Then

         System.Runtime.InteropServices.Marshal.ReleaseComObject(e)

      End If

      MyClass.Dispose()

   End Sub   ' End Dispose()

   Sub start()

      e = CreateObject("Excel.Application") 'New Excel.Application

      b = e.Workbooks.Add

      s = b.Worksheets(1)

      b.Close()

      e.Quit()

   End Sub

End Class

End Module

С закоментаренными:

Код: Выделить всё
   'GC.Collect()

   'GC.WaitForPendingFinalizers()

   'GC.Collect()

получается фигня :( Процессы EXCEL.EXE висят до закрытия программы. И даже пару раз вот такая вот картинка выскочила:

Вложения
Excel.jpg
Excel.jpg (77.36 Кб) Просмотров: 4122

В культурной столице проститутки берут книгами…


asharky
Продвинутый пользователь
Продвинутый пользователь
Аватара пользователя

 
Сообщения: 162
Зарегистрирован: 22.06.2004 (Вт) 0:39
Откуда: Батоны-ларьки-поребрики…

Сообщение asharky » 15.10.2007 (Пн) 20:03

Проблему решил. Она вообще не в той плоскости была у меня.

В культурной столице проститутки берут книгами…


ShadowTFT
Начинающий
Начинающий
 
Сообщения: 3
Зарегистрирован: 07.03.2008 (Пт) 9:02

Re: Как убить процесс Excel

Сообщение ShadowTFT » 07.03.2008 (Пт) 9:14

asn писал(а):Создаю объект Excel следующим образом:
ObjXlc = CreateObject(«Excel.Application»)
ObjXlc.Application.Workbooks.Open(Path)

Далее активирую нужную страницу,вставляю данные, сохраняю.
А вот убить процесс не получается. Пробовал
ObjXlc.close()
ObjXlc.quit()
ObjXlc=nothing
Excel продолжает висеть в процессах и умирает только когда закрываеш программу.

Что деляю не так?

Молодой человек,объясняю ситуацию… Обращение к Excel у вас идет через Com Reference, их приимущество и недостаток состоит в том, что пока не будет нофинговона последняя ссылка на данный объект, объект не завершит своий процесс жизнедеятельности. Что делать?
В принципе ваше решение ObjXlc=nothing правильно НО!!!!!
В VB.Net очистка занятие для GC (сборщика мусора). Запуск его происходит произвольно. НО!!!! Мы можем запустить его руками, его так и зовут GC нах-ся он в пространстве имен System и его метод очистки зовут Collect()… значит дописываем в ваш проэкт

asn писал(а):Создаю объект Excel следующим образом:
ObjXlc = CreateObject(«Excel.Application»)
ObjXlc.Application.Workbooks.Open(Path)

Далее активирую нужную страницу,вставляю данные, сохраняю.
А вот убить процесс не получается. Пробовал
ObjXlc.close()
ObjXlc.quit()
ObjXlc=nothing

добавляем

System.GC.Collect()

нажимаем три ласковых кнопки и смотрим результат))

вот и всё.

Приятного вам времяпрепровождения.

ShadowTFT


Sebas
Неуловимый Джо
Неуловимый Джо
Аватара пользователя

 
Сообщения: 3626
Зарегистрирован: 12.02.2002 (Вт) 17:25
Откуда: столько наглости такие вопросы задавать
  • ICQ

Сообщение Sebas » 10.03.2008 (Пн) 15:27

ShadowTFT

Уж сколько говорено, System.GC.Collect() нехорошо. Ибо делать надо 2 раза. + времени может уйти до… нескольких минут

— Я никогда не понимал, почему они приходят ко мне чтобы умирать?

sebas<-@->mail.ru


ShadowTFT
Начинающий
Начинающий
 
Сообщения: 3
Зарегистрирован: 07.03.2008 (Пт) 9:02

Сообщение ShadowTFT » 07.04.2008 (Пн) 14:15

Sebas писал(а):ShadowTFT

Уж сколько говорено, System.GC.Collect() нехорошо. Ибо делать надо 2 раза. + времени может уйти до… нескольких минут

Ну да ладно GC быстро работает, просто её не надо ждать, её надо вызвать в ручную Collect и будет вам счастье..

Ок, не хотите пользовать GC по пользуйте кострукцию With!

Код: Выделить всё
With [object]
[statements]
end with

поясняю на примере

Код: Выделить всё
With Label1
         .text = "Аргументов может быть несколько"
         .width = 300
end with

И после этого Самого «end with» все ссылки на объект сами чистятся, если мне не изменяет пампять…

В вашем случае, конструкция будет чуть сложнее:

Код: Выделить всё
With ExcelApplication.workbook(путь).Sheet(идекс листа)
     for y = 1 to 10
          for x = 1 to 100         
              str(x,y)= .cells(x,y).value
          next
     next
end with

что-то вроде того.. 8)


ShadowTFT
Начинающий
Начинающий
 
Сообщения: 3
Зарегистрирован: 07.03.2008 (Пт) 9:02

Сообщение ShadowTFT » 07.04.2008 (Пн) 14:25

Да и вообще, если по хорошему, можно просто создать ещё поток(Благо в net’е есть BackgroundWorker) и положить всё в этот поток. Как только поток закончит своё грязное дело, он закроется и все ссылки не просто Nothing’нуться, а канут в никуда.. Просто с Com компонентами всегда тяжко, не спорю, комфорт, но вот только процессы остаются весеть и Com объекты, а конкретнее Excel точно, очень медленно работаю. Я в своё время просто написал себе класс с DataTabl’ами, и читал Excel без Com’а.. Но вот к сожалению, он куда-то пропал…((



Вернуться в Visual Basic .NET

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 0

Понравилась статья? Поделить с друзьями:
  • Vba to color cells in excel
  • Vba this excel application
  • Vba sql запрос к таблице excel
  • Vba sql запрос к листу excel
  • Vba set range in excel