Disable Interop excel warning vb.net - vb.net

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

Related

Copying Datagridview to excel - leaves excel process open

Can anyone point out what is causing the excel process to remain open after my code finishes?
I've researched everything on this topic and the main point seems to be to avoid 3 dots with excel interop, but I believe I have done that and I still can't see where I'm going wrong.
my process is to copy the datagridview to the clipboard and then paste it in a newly created excel file, save it, close excel, and then give the user an option to open the file.
Two scenarios. First, when I run through the code and DON'T open the excel file it leaves the process open. Second, if I open the workbook and then close the workbook it doesn't leave a process running. I don't understand the difference because the opening of the workbook happens after I try to close and release all references to excel.
Private Sub CopyDGVtoClipBoard()
Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
Me.DataGridView1.RowHeadersVisible = False
Me.DataGridView1.SelectAll()
Dim dataObj As DataObject = Me.DataGridView1.GetClipboardContent
If dataObj IsNot Nothing Then
Clipboard.SetDataObject(dataObj)
End If
Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText
Me.DataGridView1.RowHeadersVisible = True
Me.DataGridView1.ClearSelection()
End Sub
Private Sub ExportToExcel()
If Me.DataGridView1.Rows.Count < 1 Then Exit Sub
CopyDGVtoClipBoard()
SaveFileDialog1.Filter = "Excel File|*.xlsx"
SaveFileDialog1.Title = "Save In"
SaveFileDialog1.FileName = "Generic name"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
If SaveFileDialog1.FileName <> "" Then
Dim xlExcel As excel.Application
Dim xlWorkBooks As excel.Workbooks
Dim xlWorkBook As excel.Workbook
Dim xlWorkSheet As excel.Worksheet
Dim CR As excel.Range
Dim misValue As Object = System.Reflection.Missing.Value
xlExcel = New excel.Application
xlExcel.Visible = True
xlWorkBooks = xlExcel.Workbooks
xlWorkBook = xlWorkBooks.Add(misValue)
xlWorkBook.Application.DisplayAlerts = False
xlWorkSheet = xlWorkBook.ActiveSheet
CR = xlWorkSheet.Cells(1, 1)
CR.Select()
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, True)
xlWorkBook.SaveAs(SaveFileDialog1.FileName())
xlWorkBook.Close(False)
misValue = Nothing
ReleaseExcel(CR)
ReleaseExcel(xlWorkSheet)
ReleaseExcel(xlWorkBook)
ReleaseExcel(xlWorkBooks)
xlExcel.Quit()
ReleaseExcel(xlExcel)
Dim OpenCheck As MsgBoxResult = MsgBox("Would you like to open the file?", MsgBoxStyle.YesNo, "Open File")
Dim fPath As String = SaveFileDialog1.FileName
If OpenCheck = MsgBoxResult.Yes Then
Process.Start(fPath)
End If
End If
End If
Private Sub ReleaseExcel(ByVal O As Object)
Do While System.Runtime.InteropServices.Marshal.ReleaseComObject(O) >= 0
System.Runtime.InteropServices.Marshal.ReleaseComObject(O)
Loop
O = Nothing
End Sub
I've narrowed the issue down to the below code. If I do everything except specifying a range and adding data it'll close and end the process but as soon as I reference CR = xlWorkSheet.Cells(1,1) it hangs a process
CR = xlWorkSheet.Cells(1, 1)
CR.Select()
xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, True)
Edit
So I compared my code vs. what Karen posted and made some slight adjustments to my code (full code plus changes listed below), but for some reason it works and doesn't leave a process open! Not sure how, but I'll take it.
Private Sub CopyDGVtoClipBoard()
Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
Me.DataGridView1.RowHeadersVisible = False
Me.DataGridView1.SelectAll()
Dim dataObj As DataObject = Me.DataGridView1.GetClipboardContent
If dataObj IsNot Nothing Then
Clipboard.SetDataObject(dataObj)
End If
Me.DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableWithAutoHeaderText
Me.DataGridView1.RowHeadersVisible = True
Me.DataGridView1.ClearSelection()
End Sub
Private Sub ExportToExcel()
If Me.DataGridView1.Rows.Count < 1 Then Exit Sub
CopyDGVtoClipBoard()
Dim DateCon As DateTime = DateTime.ParseExact(Today.ToShortDateString, "M/d/yyyy", Nothing)
SaveFileDialog1.Filter = "Excel File|*.xlsx"
SaveFileDialog1.Title = "Save In"
SaveFileDialog1.FileName = "Generic Name"
If SaveFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
If SaveFileDialog1.FileName <> "" Then
Dim xlExcel As excel.Application = Nothing
Dim xlWorkBooks As excel.Workbooks = Nothing
Dim xlWorkBook As excel.Workbook = Nothing
Dim xlWorkSheet As excel.Worksheet = Nothing
Dim CR As excel.Range = Nothing
Dim misValue As Object = System.Reflection.Missing.Value
xlExcel = New excel.Application
xlExcel.Visible = False
xlExcel.DisplayAlerts = False
xlWorkBooks = xlExcel.Workbooks
xlWorkBook = xlWorkBooks.Add(misValue)
xlWorkSheet = xlWorkBook.ActiveSheet
CR = xlWorkSheet.Range("A1")
CR.PasteSpecial(excel.XlPasteType.xlPasteAll)
CR.Select()
xlWorkBook.SaveAs(SaveFileDialog1.FileName)
Clipboard.Clear()
ReleaseExcel(CR)
CR = Nothing
ReleaseExcel(xlWorkSheet)
xlWorkSheet = Nothing
xlWorkBook.Close(False)
ReleaseExcel(xlWorkBook)
xlWorkBook = Nothing
ReleaseExcel(xlWorkBooks)
xlWorkBooks = Nothing
xlExcel.Quit()
ReleaseExcel(xlExcel)
xlExcel = Nothing
Dim OpenCheck As MsgBoxResult = MsgBox("Would you like to open the file?", MsgBoxStyle.YesNo, "Open File")
Dim fPath As String = SaveFileDialog1.FileName
If OpenCheck = MsgBoxResult.Yes Then
Process.Start(fPath)
End If
End If
End If
End Sub
Private Sub ReleaseExcel(ByVal O As Object)
Try
Do Until System.Runtime.InteropServices.Marshal.FinalReleaseComObject(O) = 0
System.Runtime.InteropServices.Marshal.FinalReleaseComObject(O)
Loop
Catch ex As Exception
Finally
GC.Collect()
GC.WaitForPendingFinalizers()
End Try
End Sub
The following goes along with using only two dots. After the work is done excel is properly disposed of.
Option Strict On
Option Infer Off
Imports Excel = Microsoft.Office.Interop.Excel
Imports Microsoft.Office
Imports System.Runtime.InteropServices
Module Demo1
Public Sub DoPaste()
Dim FileName As String = IO.Path.Combine(Application.StartupPath, "SomeFile.xlsx")
Dim SheetName As String = "Sheet1"
Dim Proceed As Boolean = False
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
Dim xlCells As Excel.Range = 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
Dim xlRange1 As Excel.Range = Nothing
xlRange1 = xlWorkSheet.Range("A1:B6")
xlRange1.Select()
xlRange1.Copy()
Dim xlDestination As Excel.Range = Nothing
xlDestination = xlWorkSheet.Range("C1:D6")
xlDestination.PasteSpecial(Excel.XlPasteType.xlPasteAll, Excel.XlPasteSpecialOperation.xlPasteSpecialOperationNone)
Marshal.FinalReleaseComObject(xlDestination)
xlDestination = Nothing
Marshal.FinalReleaseComObject(xlRange1)
xlRange1 = Nothing
xlWorkSheet.SaveAs(FileName)
Marshal.FinalReleaseComObject(xlWorkSheet)
xlWorkSheet = Nothing
Exit For
End If
Next
xlWorkBook.Close()
xlApp.UserControl = True
xlApp.Quit()
ReleaseComObject(xlCells)
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

Try statement not catching the exception vb.net

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

Unable to kill excel processes

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.

Export to excel vb.net

I have a problem when I export a flexgrid to excel from vb.net vs2008 to office 2010 english version an excel file is opened but it is empty. However, when I use office french version it is opened [correctly]
My code is:
On Error GoTo ErrorHandler
Dim iRow As Short
Dim iCol As Short
Dim objExcl As Excel.Application
Dim objWk As Excel.Workbook
Dim objSht As Excel.Worksheet
Dim iHead As Short
Dim vHead As Object
objExcl = New Excel.Application
objExcl.Visible = True
objExcl.UserControl = True
Dim oldCI As System.Globalization.CultureInfo = _
System.Threading.Thread.CurrentThread.CurrentCulture
System.Threading.Thread.CurrentThread.CurrentCulture = _
New System.Globalization.CultureInfo("en-US")
objWk = objExcl.Workbooks.Add
System.Threading.Thread.CurrentThread.CurrentCulture = oldCI
objSht = objWk.Sheets(1)
vHead = Split(g.FormatString, "|")
'populate heading in the sheet
'take the column heading from flex grid and put it in the sheet
For iHead = 1 To UBound(vHead)
If Len(Trim(vHead(iHead))) > 0 Then objSht.Cells._Default(1, iHead) = vHead(iHead)
Next
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
For iRow = 0 To g.Rows - 1
For iCol = 0 To g.get_Cols() - 1
g.Row = iRow
g.Col = iCol
'
'If g.Text <> "" Then objSht.Cells._Default(iRow + 2, iCol + 1) = g.Text
If g.Text <> "" Then
objSht.Range(NumCol2Lattre(iCol + 1) & "" & iRow + 2 & ":" & NumCol2Lattre(iCol + 1) & "" & iRow + 2 & "").Select()
objExcl.ActiveCell.Value = g.Text
End If
Next iCol
Next iRow
objExcl.Application.Visible = True
System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
objSht = Nothing
objWk = Nothingl may not be destroyed until it is garbage collected. Click
objExcl = Nothing
Exit Sub
ErrorHandler:
objSht = Nothing
objWk = Nothing
objExcl = Nothing
MsgBox("Error In expotation task & " & Err.Description, MsgBoxStyle.Information)
Err.Clear()
Check out this website Exporting MSFlexGrid to Excel
I suspect your problem is with vHead = Split(g.FormatString, "|") Use the debugger to find out what is the value of g.FormatString. Is it causing an error? Step through the code one line at a time and see what happens.
On Error GoTo ErrorHandler
Imports System.Data
Imports System.IO
Imports System.Web.UI
Partial Class ExportGridviewDatainVB
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not IsPostBack Then
BindGridview()
End If
End Sub
Protected Sub BindGridview()
Dim dt As New DataTable()
dt.Columns.Add("UserId", GetType(Int32))
dt.Columns.Add("UserName", GetType(String))
dt.Columns.Add("Education", GetType(String))
dt.Columns.Add("Location", GetType(String))
dt.Rows.Add(1, "SureshDasari", "B.Tech", "Chennai")
dt.Rows.Add(2, "MadhavSai", "MBA", "Nagpur")
dt.Rows.Add(3, "MaheshDasari", "B.Tech", "Nuzividu")
dt.Rows.Add(4, "Rohini", "MSC", "Chennai")
dt.Rows.Add(5, "Mahendra", "CA", "Guntur")
dt.Rows.Add(6, "Honey", "B.Tech", "Nagpur")
gvDetails.DataSource = dt
gvDetails.DataBind()
End Sub
Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
' Verifies that the control is rendered
End Sub
Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs)
Response.ClearContent()
Response.Buffer = True
Response.AddHeader("content-disposition", String.Format("attachment; filename={0}", "Customers.xls"))
Response.ContentType = "application/ms-excel"
Dim sw As New StringWriter()
Dim htw As New HtmlTextWriter(sw)
gvDetails.AllowPaging = False
BindGridview()
'Change the Header Row back to white color
gvDetails.HeaderRow.Style.Add("background-color", "#FFFFFF")
'Applying stlye to gridview header cells
For i As Integer = 0 To gvDetails.HeaderRow.Cells.Count - 1
gvDetails.HeaderRow.Cells(i).Style.Add("background-color", "#df5015")
Next
gvDetails.RenderControl(htw)
Response.Write(sw.ToString())
Response.[End]()
End Sub
End Class

Manipulating Excel files using VB8

My script is pulling some information (filename, date, &c) from a server that contains only (nearly) identical excel files generated by a separate application whenever it is used. The goal is to find out who is using the tool and how often.
I need help with two things: extracting info from within the excel file, and appending the results to the SAME excel file each time it's run instead of creating a new file each time.
Here is what I have...
Imports Excel = Microsoft.Office.Interop.Excel Imports System Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'declare excel objects
Dim xlApp As Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet
Dim misValue As Object = System.Reflection.Missing.Value
Dim i As Integer = 2
'I know this is the problem area...
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
xlWorkSheet.Cells(1, 1) = " File Name "
xlWorkSheet.Cells(1, 2) = " Date Created "
'this should be cell B1
xlWorkSheet.Cells(1, 3) = " Requestor "
'this should be cell B21
xlWorkSheet.Cells(1, 4) = " Lead Type"
'get to directory
For Each strFolder As String In _
My.Computer.FileSystem.GetDirectories("Z:\\...")
'get file names
Dim infoReader As System.IO.FileInfo
infoReader = My.Computer.FileSystem.GetFileInfo(strFolder)
'write to excel worksheet
xlWorkSheet.Cells(i, 1) = strFolder
xlWorkSheet.Cells(i, 2) = infoReader.CreationTime
i += 1
Next
xlWorkSheet.SaveAs("C:\...")
xlWorkBook.Close()
xlApp.Quit()
releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)
MsgBox("Excel file created , see file in c:\Documents")
End Sub
Private Sub releaseObject(ByVal obj As Object)
Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub
Instead of creating a new application and workbook, just use activeworkbook, e.g.
replace
'I know this is the problem area...
xlApp = New Excel.Application
xlWorkBook = xlApp.Workbooks.Add(misValue)
xlWorkSheet = xlWorkBook.Sheets("sheet1")
with
xlWorkBook = xlApp.ActiveWorkbook
xlWorkSheet = xlWorkBook.Sheets("sheetname")
where you replace sheetname with whatever the desired sheet name is.
Alternatively, you could just use ActiveSheet.