My exception isn't working for an excel file that is searched and returned with information. Below you will see that it cycles through the first column and returns information according to variables that are set globally. I have put an exception that if the try fails a message box will pop up and tell them it failed to find them, but its not catching it. Instead if the user isn't listed in the database it freezes the program.
Private Sub ExceptionToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExceptionToolStripMenuItem.Click
Dim objexcel As New Excel.Application
Dim objWorkbook As Excel.Workbook
Dim objWorksheet As Excel.Worksheet
objexcel.DisplayAlerts = False
If Global_Variables.SavedResults.UserM = Nothing And Global_Variables.SavedResults.UserL = Nothing Then
objWorkbook = objexcel.Workbooks.Open("filepath", [ReadOnly]:=True)
objWorksheet = CType(objWorkbook.Worksheets.Item("Sheet1"), Excel.Worksheet)
Try
For x As Integer = 1 To objWorksheet.Rows.Count Step 1
If objWorksheet.Cells(x, 1).value = Global_Variables.SavedResults.UserD Then
Global_Variables.SavedResults.UserL = objWorksheet.Cells(x, 3).value
Global_Variables.SavedResults.UserM = objWorksheet.Cells(x, 2).value
Exit For
End If
Next
Exit Try
Catch ex As Exception
MsgBox("You are not in the Database.")
End Try
objWorkbook.Close()
objexcel.Quit()
ReleaseObject(objWorksheet)
ReleaseObject(objWorkbook)
ReleaseObject(objexcel)
objWorkbook = Nothing
objWorksheet = Nothing
objexcel = Nothing
End If
Dim Email As New Email_Templates
Email.Exception()
End Sub
Related
in VB.Net I am trying to copy the entire contents of a Word Document and then paste the clipboard into an email body. Populating the clipboard was easy but I am not sure how to use it in the contents of the email body.
here is my failed code.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim objWord
Dim wordPath
Dim currentDocument
Dim myRange
wordPath = "C:\Users\user.on.computer\OneDrive\_My Clients\_Older Clients\ASG\Trip Reports\ASG TOOLS 20170320 BAM3.docx"
objWord = CreateObject("Word.Application")
objWord.Documents.Open(wordPath, False, True)
currentDocument = objWord.Documents(1)
myRange = currentDocument.Range
myRange.WholeStory
myRange.Copy
Dim objOutl, objMailItem, strEmailAddr
objOutl = CreateObject("Outlook.Application")
objMailItem = objOutl.CreateItem(0)
Dim iData As IDataObject = Clipboard.GetDataObject()
strEmailAddr = "me#somewhere.com"
objMailItem.Recipients.Add(strEmailAddr)
objMailItem.HTMLBody = iData.GetData("String")
objMailItem.Subject = "Testing Process"
objMailItem.Attachments.Add(wordPath)
objMailItem.Save
objMailItem = Nothing
objOutl = Nothing
objWord = Nothing
End Sub
I am hoping its an easy fix, thanks.
Here is how you can do it
With objMailItem.GetInspector
.WordEditor.Content.Paste
.Close 0
End With
I want to make a code which will send a textbox value to an excel worksheet. Every time i press the button the text box value shoud replace the previous one. What i ve already done is just send this value to an excel worksheet, but in every new click there is a new Workbook opening. what should i change ?
here is the code
Imports System.Data.OleDb
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Dim objApp As Excel.Application
Dim objBook As Excel._Workbook
Dim objBooks As Excel.Workbooks
Dim objSheets As Excel.Sheets
Dim objSheet As Excel._Worksheet
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Create a new instance of Excel and start a new workbook.
objApp = New Excel.Application()
objBooks = objApp.Workbooks
objBook = objBooks.Add
objSheets = objBook.Worksheets
objSheet = objSheets(1)
objSheet.Range("A1").Value = TextBox1.Text
'Return control of Excel to the user.
objApp.Visible = True
objApp.UserControl = True
'Clean up a little.
objSheet = Nothing
objSheets = Nothing
objBooks = Nothing
End Sub
End Class
Change this:
objApp = New Excel.Application()
In
If objApp Is Nothing Then
objApp = New Excel.Application()
End If
I'd simplify as follows:
Public Class Form1
Dim objApp As Excel.Application
Dim objCell As Excel.Range
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If objCell Is Nothing Then
objApp = New Excel.Application()
objCell = objApp.Workbooks.Add.Worksheets(1).Range("A1")
End If
objCell.Value = TextBox1.Text
'Return control of Excel to the user.
objApp.Visible = True
objApp.UserControl = True
End Sub
End Class
this code should be made more robust to handle such situation as user closing Excel
this finally did the job
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If objApp Is Nothing Then
objApp = New Excel.Application()
End If
If objBooks Is Nothing Then
objBooks = objApp.Workbooks
End If
If objBook Is Nothing Then
objBook = objBooks.Add
End If
If objSheets Is Nothing Then
objSheets = objBook.Worksheets
End If
If objSheet Is Nothing Then
objSheet = objSheets(1)
End If
objSheet.Range("A1").Value = TextBox1.Text
'Return control of Excel to the user.
objApp.Visible = True
objApp.UserControl = True
'Clean up a little.
objSheet = Nothing
objSheets = Nothing
objBooks = Nothing
End Sub
thank you all for your responses
I am trying to figure how to set the active workbook and active sheet as a variable I can reference later. I have my script set up, and I placed ????'s in the areas where I assume I would put the reference.
Any suggetsions?
Dim oXL As Application
Dim oWB As Microsoft.Office.Interop.Excel.Workbook
Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim oRng As Microsoft.Office.Interop.Excel.Range
oWB = ????
oSheet = ?????
Added info from comment to Karen Payne's answer:
I am trying to reference an existing one I already have open, that is
the active window at the time of using my application.
i.e.: How can I attach to an open Excel instance and retrieve a reference to the ActiveWorkbook?
Perhaps the following will help. It is a demo that sets the active sheet in xlWorkSheet that can be used as you see fit.
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module SetDefaultWorkSheetCode
Public Sub SetDefaultSheet(ByVal FileName As String, ByVal SheetName As String)
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
For x As Integer = 1 To xlWorkSheets.Count
xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
If xlWorkSheet.Name = SheetName Then
xlWorkSheet.Activate()
xlWorkSheet.SaveAs(FileName)
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Exit For
End If
Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Next
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End Sub
Private Sub ReleaseComObject(ByVal obj As Object)
Try
If obj IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
End If
Catch ex As Exception
obj = Nothing
End Try
End Sub
End Module
With those Excel objects, you have to assign values to them using the "Set" keyword. For example:
Set oWB = ActiveWorkbook
Here are two techniques for attaching to a running Excel instance. I think the method shown in 'Button1_Click' is one you are seeking, but I also showed second method that looks in the Running Object Table (ROT) for a matching Workbook name.
Imports System.Runtime.InteropServices
Imports Microsoft.Office.Interop
Public Class Form1
Private WithEvents ExcelCleanUpTimer As New Timer With {.Interval = 100}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim app As Excel.Application
Try ' to attach to any Excel instance
app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
Catch ex As Exception
MessageBox.Show("No Excel instances found")
Exit Sub
End Try
' take over responsibility for closing Excel
app.UserControl = False
app.Visible = False
Dim activeWB As Excel.Workbook = app.ActiveWorkbook
Dim activeSheet As Object = app.ActiveSheet
' determine if ActiveSheet is a Worksheet or Chart
' if it is a Worksheet, activeChart is Nothing
' if it is a Chart, activeWorksheet is Nothing
Dim activeWorksheet As Excel.Worksheet = TryCast(activeSheet, Excel.Worksheet)
Dim activeChart As Excel.Chart = TryCast(activeSheet, Excel.Chart)
If activeWorksheet IsNot Nothing Then
For Each cell As Excel.Range In activeWorksheet.Range("A1:A20")
cell.Value2 = "hello"
Next
End If
'shut Excel down, don't save anything
app.DisplayAlerts = False
app.Workbooks.Close()
app.Quit()
' using a timer lets any ComObj variables in this method go out of context and
' become eligible for finalization. GC's call to RCW wrapper finalizer will
' release its reference counts on Excel
ExcelCleanUpTimer.Start()
End Sub
Private Sub ExcelCleanUpTimer_Tick(sender As Object, e As EventArgs) Handles ExcelCleanUpTimer.Tick
ExcelCleanUpTimer.Stop()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' if this is a saved Workbook, the path will be the full file path
Dim path As String = "Book1" ' or the full file path to a workbook including the extension
Dim activeWorkbook As Excel.Workbook = Nothing
Try
' this technique differs for Marshal.GetActiveObject in that if the path
' is a valid file path to an Excel file and Excel is not running, it will
' launch Excel to open the file.
activeWorkbook = CType(Marshal.BindToMoniker(path), Excel.Workbook)
Catch ex As Exception
' an exception will be throw if 'path' is not found in the Runinng Object Table (ROT)
MessageBox.Show(path & " not found")
Exit Sub
End Try
Dim app As Excel.Application = activeWorkbook.Application
app.Visible = True
app.UserControl = True
' the wb window will be hidden if opening a file
activeWorkbook.Windows(1).Visible = True
ExcelCleanUpTimer.Start()
End Sub
End Class
Sorry about my last answer.. I didn't see that you were trying to do it in .NET. Anyway, just like in the context of Excel, you have to first open or create all of the workbooks that you want to work with. If you already have it open, then you can use the file name of the workbook you want to assign it to a workbook variable..
xlWorkbook = xlApp.Workbooks.Item("filename of the workbook already open")
Here is the same code, partly commented out as to the activate part and I added in code to show how to get the current active sheet.
Option Strict On
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module SheetCode
Public Sub SetDefaultSheet(ByVal FileName As String, ByVal SheetName As String)
Dim xlApp As Excel.Application = Nothing
Dim xlWorkBooks As Excel.Workbooks = Nothing
Dim xlWorkBook As Excel.Workbook = Nothing
Dim xlWorkSheet As Excel.Worksheet = Nothing
Dim xlWorkSheets As Excel.Sheets = Nothing
xlApp = New Excel.Application
xlApp.DisplayAlerts = False
xlWorkBooks = xlApp.Workbooks
xlWorkBook = xlWorkBooks.Open(FileName)
xlApp.Visible = False
xlWorkSheets = xlWorkBook.Sheets
'
' Here I added how to get the current active worksheet
'
Dim ActiveSheetInWorkBook As Excel.Worksheet = CType(xlWorkBook.ActiveSheet, Excel.Worksheet)
Console.WriteLine(ActiveSheetInWorkBook.Name)
Runtime.InteropServices.Marshal.FinalReleaseComObject(ActiveSheetInWorkBook)
ActiveSheetInWorkBook = Nothing
'For x As Integer = 1 To xlWorkSheets.Count
' xlWorkSheet = CType(xlWorkSheets(x), Excel.Worksheet)
' If xlWorkSheet.Name = SheetName Then
' xlWorkSheet.Activate()
' xlWorkSheet.SaveAs(FileName)
' Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
' xlWorkSheet = Nothing
' Exit For
' End If
' Runtime.InteropServices.Marshal.FinalReleaseComObject(xlWorkSheet)
' xlWorkSheet = Nothing
'Next
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlWorkSheets)
ReleaseComObject(xlWorkSheet)
ReleaseComObject(xlWorkBook)
ReleaseComObject(xlWorkBooks)
ReleaseComObject(xlApp)
End Sub
Private Sub ReleaseComObject(ByVal obj As Object)
Try
If obj IsNot Nothing Then
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
End If
Catch ex As Exception
obj = Nothing
End Try
End Sub
End Module
Currently working on a project where I automatically track individual users system lock/unlock time and write that information to an excel sheet placed on network drive (using INTEROP). This exe is placed on the system startup so that when the user logins it automatically starts. The idea behind this application is to track user locked/unlocked time to calculate their utilization without user knowledge (Personally I would hate this kind of hidden approach, but this is what I’m expected to come up with)
The exe works absolutely fine till the time the user is on the office network, but the problem is if the user logs in from home then he will be out of the network till the time he connects to the VPN. But if the user locks/unlocks the system before he gets on the VPN, the tool throws an error "Microsoft Excel cannot open the file, check spelling or path".
I don’t want this to happen because the tool is throwing the path along with the error and the whole purpose of having this application hidden goes for a toss. Just wanted to check with you guys if there is anyway I can suppress this error message and close this application if this happens.
Any help on this will be very useful. I have given the code below
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.Visible = False
Me.ShowInTaskbar = False
Timer1.Start()
Timer1.Interval = 100
RichTextBox1.Text = ""
End Sub
Private Sub WorkStationReader_locked(ByVal ivarreturn As Object) Handles WorkStationReader.locked
If ivarreturn(1) = True And Locked = False Then
Locked = True
''MsgBox(ivarreturn(0).ToString)
' MsgBox(ivarreturn(0).ToString & "" & Date.Now.ToString)
RichTextBox1.Text += ivarreturn(0).ToString & "" & Date.Now.ToString
RichTextBox1.Text += vbCrLf
Dim xlApp As Microsoft.Office.Interop.Excel.Application
xlApp = New Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
xlApp.Visible = False
Try
Dim xlBook As Excel.Workbook = xlApp.Workbooks.Open("\\99.99.999.99\Excel\Satish.xlsx")
Dim xlSheet As Excel.Worksheet = xlBook.ActiveSheet
Dim xlSheet2 As Excel.Worksheet = xlBook.Worksheets("Sheet1")
' xlSheet2.Range("B5").Value2 = "my new string"
Dim iRow As Integer
iRow = 1
With xlApp
Do While .Cells(iRow, 1).value <> ""
.Cells(iRow, 1).activate()
iRow = iRow + 1
Loop
.Cells(iRow, 1).value = ivarreturn(0).ToString & "" & Date.Now.ToString
End With
xlBook.Save()
xlApp.Quit()
Dim strX As String = RichTextBox1.SelectedText
'if no text is selected, copy the entire text
If strX.Length = 0 Then strX = RichTextBox1.Text
'Copy data if any to copy
If strX.Length > 0 Then
Clipboard.SetDataObject(strX)
End If
Catch ex As Exception
MessageBox.Show("Can not open connection ! ")
End Try
End If
If ivarreturn(1) = False And Locked = True Then
Locked = False
RichTextBox1.Text += ivarreturn(0).ToString & "" & Date.Now.ToString
RichTextBox1.Text += vbCrLf
''MsgBox(ivarreturn(0).ToString)
Dim xlApp As Microsoft.Office.Interop.Excel.Application
xlApp = New Microsoft.Office.Interop.Excel.Application
Dim xlWorkBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlWorkSheet As Microsoft.Office.Interop.Excel.Worksheet
xlApp.Visible = False
Dim xlBook As Excel.Workbook = xlApp.Workbooks.Open("\\99.99.999.99\Excel\Satish.xlsx")
Dim xlSheet As Excel.Worksheet = xlBook.ActiveSheet
Dim xlSheet2 As Excel.Worksheet = xlBook.Worksheets("Sheet1")
' xlSheet2.Range("B5").Value2 = "my new string"
Dim iRow As Integer
iRow = 1
With xlApp
Do While .Cells(iRow, 2).value <> ""
.Cells(iRow, 2).activate()
iRow = iRow + 1
Loop
.Cells(iRow, 2).value = ivarreturn(0).ToString & "" & Date.Now.ToString
End With
xlBook.Save()
xlApp.Quit()
End If
End Sub
Private Sub Timer1_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles Timer1.Tick
WorkStationReader.WorkStationISLocked()
End Sub
Have you tried wrapping your code with Try / Catch blocks? You can Try your code, if it throws an Exception then catch it in the Catch block. You can then call Me.Close() if an exception is thrown. This will "handle" the error and close the program without notifying the user.
Try
'Do some Interop stuff here
Catch(E As Exception)
Me.Close()
End Try
I am using the followiwing code to do some copying and pasting with excel files:
Imports Excel = Microsoft.Office.Interop.Excel
Imports System.IO
Imports System.Runtime.InteropServices
Private Sub btnCombine_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCombine.Click
Dim xlAppSource As New Excel.Application
Dim xlAppTarget As New Excel.Application
Dim xlWbSource As Excel.Workbook
Dim xlWbTarget As Excel.Workbook
Dim xlsheetSource As Excel.Worksheet
Dim xlsheetTarget As Excel.Worksheet
Dim xlRangeSource As Excel.Range
Dim xlRangeTarget As Excel.Range
Dim Progress As Integer = 0
pbrProgress.Minimum = 0
pbrProgress.Maximum = amountOfFiles
btnCombine.Enabled = False
btnSelect.Enabled = False
pbrProgress.Visible = True
getSaveLocation()
MakeExcelFile()
'loop through all excel files to get the required data
For i = 0 To amountOfFiles - 1
Dim CurrentFile As String = strFileNames(i)
Dim IntAmountOfRows As Integer = amountOfRows(CurrentFile)
Dim intStartOfEmptyRow As Integer = amountOfRows(SummaryLocation)
xlAppSource.DisplayAlerts = False
xlAppTarget.DisplayAlerts = False
'Set current workbook
xlWbSource = xlAppSource.Workbooks.Open(CurrentFile)
xlWbTarget = xlAppTarget.Workbooks.Open(SummaryLocation)
'set current worksheet
xlsheetSource = xlWbSource.ActiveSheet
xlsheetTarget = xlWbTarget.ActiveSheet
'copy range of data from source to target file
xlRangeSource = xlsheetSource.Range("A2:k" & IntAmountOfRows)
xlRangeSource.Copy()
xlRangeTarget = xlsheetTarget.Range("A" & intStartOfEmptyRow)
xlRangeTarget.PasteSpecial(Excel.XlPasteType.xlPasteValues)
'save summary file before closing
xlsheetTarget.SaveAs(SummaryLocation)
'updating progress bar
Progress = Progress + 1
pbrProgress.Value = Progress
Next
'close excel
xlWbSource.Close(True)
xlWbTarget.Close(True)
xlAppSource.Quit()
xlAppTarget.Quit()
xlAppSource.DisplayAlerts = True
xlAppTarget.DisplayAlerts = True
'Cleanup
Marshal.ReleaseComObject(xlAppSource)
Marshal.ReleaseComObject(xlAppTarget)
Marshal.ReleaseComObject(xlWbSource)
Marshal.ReleaseComObject(xlWbTarget)
Marshal.ReleaseComObject(xlsheetSource)
Marshal.ReleaseComObject(xlsheettarget)
Marshal.ReleaseComObject(xlRangeSource)
Marshal.ReleaseComObject(xlRangeTarget)
xlAppSource = Nothing
xlAppTarget = Nothing
xlWbSource = Nothing
xlWbTarget = Nothing
xlsheetSource = Nothing
xlsheetTarget = Nothing
xlRangeSource = Nothing
xlRangeTarget = Nothing
MsgBox("Samenvoegen compleet")
init()
End Sub
I have tried every solution given on SO:
Never use 2 points on a line
I have tried using marshall.ReleaseComObject
I have tried setting the objects to "Nothing"
However, everytime I run the application, there will be 10-20 excel processes still running.
Option Explicit
Sub Main()
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
xlApp.Visible = False
xlApp.DisplayAlerts = False
Dim xlWb As Workbook
Set xlWb = xlApp.Workbooks.Open("C:\...\path")
Dim xlSht As Worksheet
Set xlSht = xlWb.Sheets(1)
xlSht.Range("A1") = "message from " & ThisWorkbook.FullName
xlWb.Saved = True
xlWb.Save
xlWb.Close
xlApp.Quit
End Sub
Works for me every single time and does not leave any Excel processes hanging in the task manager.
Note: if your code breaks at some point and you do not handle the already opened objects properly then they will just hang in the processes tab in the Task Manager. If you haven't implemented error handling in your code then start here.
just consider this as alternative
Option Explicit
Sub Main()
On Error GoTo ErrHandler
Dim xlApp As Excel.Application
Set xlApp = New Excel.Application
xlApp.Visible = False
xlApp.DisplayAlerts = False
Dim xlWb As Workbook
Set xlWb = xlApp.Workbooks.Open("C:\...\path")
Dim xlSht As Worksheet
Set xlSht = xlWb.Sheets(1)
xlSht.Range("A1") = "message from " & ThisWorkbook.FullName
xlWb.Saved = True
xlWb.Save
xlWb.Close
xlApp.Quit
Exit Sub
ErrHandler:
xlWb.Saved = True
xlWb.Save
xlWb.Close
xlApp.Quit
End Sub
The Interop Marshal release doesn't always work because Excel XP and lower suck at releasing. I had to use your loop, but replace the Process.Close() and Process.Quit() with Process.Kill(). Works like a charm. Just be careful that you want ALL versions of excel.exe to be killed, because they will.
I use this:
Workbook.Save()
Workbook.Close()
Application.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(Application)
Worksheet = Nothing
Workbook = Nothing
Application = Nothing
Dim proc As System.Diagnostics.Process
For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
proc.Kill()
Next
When you do anything with the Excel Interop, it creates a new process.
The problem with killing all Excel processes is that you may kill a process that you are working with. You can kill all processes which have been running for a certain length of time (i.e. from a certain timestamp) with:
Dim proc As System.Diagnostics.Process
Dim info As ManagementObject
Dim search As New ManagementObjectSearcher("SELECT ProcessId FROM Win32_process WHERE caption = 'Excel'")
For Each info In search.Get()
'The string will give you the time that the process started
'You can then subtract that from the current time to see if you want to kill the process
Dim TheString As String = info.GetText(TextFormat.Mof).ToString
'Kill the process according to its ID
proc = System.Diagnostics.Process.GetProcessById(Mid$(TheString, _
(Len(TheString) - 8), 4))
proc.CloseMainWindow()
proc.Refresh()
If proc.HasExited Then GoTo NoKill
proc.Kill()
NoKill:
Next
You'll need to add:
Imports System.Management
and add the reference for the 'System.Management' to your project.
You can obtain the process ID from the Excel.Application hwnd and use that to kill the process safely.