Results 1 to 7 of 7

Thread: Problem using Excel with VB.Net

  1. #1

    Thread Starter
    Addicted Member Porsche944's Avatar
    Join Date
    Apr 2005
    Location
    Ann Arbor
    Posts
    182

    Exclamation Problem using Excel with VB.Net

    Hey guys,
    I am trying to get my program to create an excel file and populate it with data from my program. I have attached the code I am using.

    If excel is not open I receive an error that says "Cannot create ActiveX componet"

    if excel is open I receive this error " "could not be found. Check the spelling of the file name, and verify that the file location is correct"
    I believe this error is coming up becuase the dialog box has not yet been created and the filename retrieved from the user.

    I do not want to have to have excel open in order to create an excel file with some data in it. Is there another way to do this? Is it possible to start excel automaicly and hide it from the user so they don't notice it being open?

    Code:
            Dim intCount As Integer = 0
            Dim strMachine As String
            Dim strTemp As String
            Dim strDescription As String
            Dim strFinal As String
            Dim bolTestcb As Boolean
            Dim hashSave As New Hashtable
            Dim intExcelCount As Integer = 0
            Dim intX As Integer = 0
            Dim byteCol As Byte = 0
            Dim bolExcel As Boolean = False
            Dim intExcelRow As Integer = 0
    
    
            Dim oWB As Excel.Workbook
    
            Dim bOpen As Boolean
    
            If rbExcel.Checked = True Then
                bolExcel = True
                Try
                    oApp = GetObject(, "Excel.Application")
                    If oApp Is Nothing Then oApp = New Excel.Application
                    For Each oWB In oApp.Workbooks
                        If oWB.Name = dlgSave.FileName Then
                            bOpen = True
                            Exit For
                        Else
                            bOpen = False
                        End If
                    Next
                    If bOpen = True Then
                        'Already open
                        oWB = oApp.Workbooks(dlgSave.FileName)
                    Else
                        'Open your wb
                        oWB = oApp.Workbooks.Open(dlgSave.FileName)
                    End If
                    oApp.Visible = True
    
                Catch exp As Exception
                    MessageBox.Show(exp.Message, exp.Source, MessageBoxButtons.OK, MessageBoxIcon.Error)
                End Try
            End If

  2. #2
    Frenzied Member Asgorath's Avatar
    Join Date
    Sep 2004
    Location
    Saturn
    Posts
    2,036

    Re: Problem using Excel with VB.Net

    Set it invisible
    VB Code:
    1. oApp.Visible = False
    and declare it has public.

    Regards
    Jorge
    "The dark side clouds everything. Impossible to see the future is."

  3. #3

    Thread Starter
    Addicted Member Porsche944's Avatar
    Join Date
    Apr 2005
    Location
    Ann Arbor
    Posts
    182

    Exclamation Re: Problem using Excel with VB.Net

    Quote Originally Posted by Asgorath
    Set it invisible
    VB Code:
    1. oApp.Visible = False
    and declare it has public.

    Regards
    Jorge
    what varible do you suggest i declare as public?

    That still won't stop the program from crashing if excel is not currently open.

  4. #4
    Frenzied Member Asgorath's Avatar
    Join Date
    Sep 2004
    Location
    Saturn
    Posts
    2,036

    Re: Problem using Excel with VB.Net

    I use the following code samples on my app and it works perfectly.

    Put this on the top of class/form declaration
    VB Code:
    1. Option Explicit On
    2. Option Strict On



    To open a existing workbook:
    VB Code:
    1. Dim objExcel As new Excel.Application
    2.         Dim Books As Excel.Workbooks
    3.         Dim Book As Excel.Workbook
    4.         Dim Sheet As Excel.Worksheet
    5.  
    6.  
    7.         objExcel.Visible = True
    8.         Books = objExcel.Workbooks
    9.         '' open  the book
    10.         Book = Books.Open(FileName)
    11.         Sheet = DirectCast(Book.Worksheets(1), Excel.Worksheet)
    12.  
    13.  
    14.         DirectCast(Book.Sheets("Sheet1"), Excel.Worksheet).Activate()
    15.         Sheet = DirectCast(Book.ActiveSheet, Excel.Worksheet)


    To create a new workbook :
    VB Code:
    1. Dim objApp As New Excel.Application
    2.         Dim objBook As Excel.Workbook = objApp.Workbooks.Add
    3.         Dim objSheet As Excel.Worksheet = DirectCast(objApp.ActiveSheet, Excel.Worksheet)
    4.  
    5.     objSheet.Range("A1).Value = "Hello"
    6.     messagebox.show(objSheet.Range("A1").Text.ToString)
    7.  
    8.     objBook.SaveAs(FileName)
    9.  
    10.     objBook.Close
    11.     objApp.Quit
    12.    
    13.     System.Runtime.InteropServices.Marshal.ReleaseComObject(objApp)

    Regards
    Jorge
    "The dark side clouds everything. Impossible to see the future is."

  5. #5
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Problem using Excel with VB.Net

    Here's a class I use as a base for dealing with Excel stuff.


    VB Code:
    1. Public Class ExcelHolder
    2.     Implements System.IDisposable
    3.  
    4.     'the app and state members.
    5.     Protected xlApp As Microsoft.Office.Interop.Excel.Application
    6.     Protected ImOpen As Boolean
    7.  
    8.     'A book
    9.     Protected xlBook As Microsoft.Office.Interop.Excel.Workbook
    10.  
    11.     'A few sheet members.
    12.     Protected mSheetNo As Integer
    13.     Protected mNewBook As Boolean
    14.     Protected mBookName As String
    15.     Protected mSheetName As String
    16.  
    17. #Region "Constructors and Destructors"
    18.  
    19.     Public Sub New()
    20.         'This does not open the app.
    21.         ImOpen = False
    22.         mSheetNo = 1
    23.         mNewBook = True
    24.         mBookName = ""
    25.     End Sub
    26.  
    27.     Public Sub Dispose() Implements System.IDisposable.Dispose
    28.         If Not xlBook Is Nothing Then
    29.             Try
    30.                 xlBook.Close()
    31.             Catch ex As Exception
    32.                 'Do Nothing.
    33.             End Try
    34.         End If
    35.         If Not xlApp Is Nothing Then
    36.             Try
    37.                 xlApp.Quit()
    38.             Catch ex As Exception
    39.                 Windows.Forms.MessageBox.Show("Excel App didn't close. You should never see this error. It is particularly bad, because it doesn't appear to cause problems.", "Hidden Issue", MessageBoxButtons.OK, MessageBoxIcon.Hand)
    40.             End Try
    41.         End If
    42.     End Sub
    43.  
    44. #End Region
    45.  
    46. #Region "Properties"
    47.  
    48.     Public Property NewBook() As Boolean
    49.         Get
    50.             NewBook = mNewBook
    51.         End Get
    52.  
    53.         Set(ByVal Value As Boolean)
    54.             mNewBook = Value
    55.             If Value Then
    56.                 If Not xlBook Is Nothing Then
    57.                     xlBook.Save()
    58.                     xlBook.Close()
    59.                     xlBook = Nothing
    60.                 End If
    61.                 mBookName = ""
    62.                 mSheetNo = 1
    63.             End If
    64.         End Set
    65.  
    66.     End Property
    67.  
    68. #End Region
    69.  
    70. #Region "Public Functions"
    71.  
    72.     'This function is used to save data to the current book. If there is no current book,
    73.     'then a new one is opened for it.
    74.     Public Function SaveDataOld(ByRef dr As System.Data.OleDb.OleDbDataReader) As Boolean
    75.         Dim fileNam As String
    76.         Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
    77.         Dim flag As Boolean
    78.         Dim x As Integer
    79.         Dim y As Integer
    80.         Dim v As Integer
    81.  
    82.         'Check for an open app.
    83.         If Not ImOpen Then
    84.             If Not OpenApp() Then
    85.                 Windows.Forms.MessageBox.Show("Failed to open the Excel App.", "No Can DOH!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    86.                 SaveDataOld = False
    87.                 Exit Function
    88.             End If
    89.         End If
    90.  
    91.         'Now dump the data.
    92.         Try
    93.             'If this is a new book.
    94.             If mNewBook Then
    95.                 xlBook = xlApp.Workbooks.Add
    96.             End If
    97.             'Get the first sheet.
    98.             xlSheet = xlBook.Worksheets(mSheetNo)
    99.  
    100.             xlSheet.Cells.Clear()
    101.             If mSheetName <> "" Then
    102.                 xlSheet.Name = mSheetName
    103.             End If
    104.  
    105.             'Set the flag so the names can be written.
    106.             flag = True
    107.             y = 2
    108.  
    109.             'The loop.
    110.             Do While dr.Read
    111.                 'In the first round, put the names in.
    112.                 If flag Then
    113.                     flag = False
    114.                     v = dr.FieldCount
    115.                     For x = 0 To v - 1
    116.                         xlSheet.Cells(1, x + 1) = dr.GetName(x)
    117.                     Next
    118.                 End If
    119.  
    120.                 'This is the standard.
    121.                 For x = 0 To v - 1
    122.                     xlSheet.Cells(y, x + 1) = dr.Item(x)
    123.                 Next
    124.  
    125.                 'Increment the row counter.
    126.                 y += 1
    127.             Loop
    128.  
    129.             If mNewBook Then
    130.                 If Not SetBookName() Then
    131.                     'NOTE: This is an early exit condition. If the book name failed, then
    132.                     'it is important that everything beyond this is not executed.
    133.                     Windows.Forms.MessageBox.Show("Data NOT saved. No valid filename.", "Not Saved", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
    134.                     xlBook.Close()
    135.                     Return False
    136.                 End If
    137.             End If
    138.  
    139.             'Now the data has been put away. Save the book.
    140.  
    141.             If mNewBook Then
    142.                 xlBook.SaveAs(mBookName)
    143.             Else
    144.                 xlBook.Save()
    145.             End If
    146.  
    147.             'Increment the sheet number.
    148.             mSheetNo += 1
    149.             Windows.Forms.MessageBox.Show("Data saved.", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information)
    150.             'Keep the book open.
    151.             NewBook = False
    152.             SaveDataOld = True
    153.         Catch ex As Exception
    154.             MsgBox("Something failed while writing the data." & vbNewLine & vbNewLine & ex.Message, MsgBoxStyle.Exclamation, "Failure")
    155.             SaveDataOld = False
    156.         End Try
    157.  
    158.     End Function
    159.     Public Function SaveDataOld(ByRef dr As System.Data.OleDb.OleDbDataReader, ByVal shtName As String) As Boolean
    160.         mSheetName = shtName
    161.         Return SaveDataOld(dr)
    162.     End Function
    163.  
    164.     'Use this function to save always to a new book. The book will remain open.
    165.     Public Function SaveDataNewBook(ByRef dr As System.Data.OleDb.OleDbDataReader) As Boolean
    166.         NewBook = True
    167.         'Now, just call this basic function to do all the work.
    168.         SaveDataNewBook = SaveDataOld(dr)
    169.     End Function
    170.     Public Function SaveDataNewBook(ByRef dr As System.Data.OleDb.OleDbDataReader, ByVal shtName As String) As Boolean
    171.         mSheetName = shtName
    172.         Return SaveDataNewBook(dr)
    173.     End Function
    174.  
    175.     'This is just here in case there is an advantage to not maintaining the app. If there
    176.     'is an open book, it is closed by setting the newbook to true.
    177.     Public Function CloseApp()
    178.         NewBook = True
    179.         If Not xlApp Is Nothing Then
    180.             xlApp.Quit()
    181.         End If
    182.     End Function
    183.  
    184. #End Region
    185.  
    186. #Region "Private Functions"
    187.  
    188.     Protected Function SetBookName() As Boolean
    189.         Dim flNm As String
    190.         Dim cdlg1 As New System.Windows.Forms.SaveFileDialog
    191.         Dim st1 As String
    192.  
    193.         SetBookName = False
    194.  
    195.         flNm = ""
    196.         mBookName = ""
    197.         Do
    198.             'Get it.
    199.             cdlg1.FileName = flNm
    200.             cdlg1.Filter = "Excel Files (*.xls)|*.xls"
    201.             cdlg1.CheckFileExists = False
    202.             cdlg1.OverwritePrompt = False
    203.             If cdlg1.ShowDialog() = DialogResult.Cancel Then
    204.                 'The user opted to cancel. Bail out.
    205.                 flNm = "Blue"
    206.             Else
    207.                 flNm = cdlg1.FileName
    208.  
    209.                 'Check it.
    210.                 If System.IO.File.Exists(flNm) Then
    211.                     'If it exists, warn on it.
    212.                     If Windows.Forms.MessageBox.Show("That file already exists. If you use it, you will overwrite at least one of the sheets in the existing spreadsheet. Is this what you want to do?", "Watch Out", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) = DialogResult.No Then
    213.                         flNm = ""
    214.                     Else
    215.                         mBookName = flNm
    216.                     End If
    217.                 Else
    218.                     mBookName = flNm
    219.                 End If
    220.             End If
    221.         Loop While flNm = ""
    222.  
    223.         'Only have to check one thing for the return value.
    224.         If mBookName <> "" Then
    225.             SetBookName = True
    226.         End If
    227.  
    228.     End Function
    229.  
    230.     Protected Function OpenApp() As Boolean
    231.         'Create the app.
    232.         Try
    233.             If xlApp Is Nothing Then
    234.                 xlApp = CType(CreateObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
    235.             End If
    236.             xlApp.AlertBeforeOverwriting = False
    237.             ImOpen = True
    238.         Catch ex As Exception
    239.             ImOpen = False
    240.         End Try
    241.  
    242.         OpenApp = ImOpen
    243.     End Function
    244.  
    245. #End Region
    246.  
    247.    
    248. End Class
    My usual boring signature: Nothing

  6. #6
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    40,106

    Re: Problem using Excel with VB.Net

    You don't actually see Excel running with that class, though I don't do anything interesting to keep it hidden. This requires that Excel 2003 exists, and has the .NET programmability component installed. Also, you will have to include the Excel Object library, but I believe you have already done that.
    My usual boring signature: Nothing

  7. #7

    Thread Starter
    Addicted Member Porsche944's Avatar
    Join Date
    Apr 2005
    Location
    Ann Arbor
    Posts
    182

    Re: Problem using Excel with VB.Net

    Quote Originally Posted by Shaggy Hiker
    You don't actually see Excel running with that class, though I don't do anything interesting to keep it hidden. This requires that Excel 2003 exists, and has the .NET programmability component installed. Also, you will have to include the Excel Object library, but I believe you have already done that.
    I'll try your class out when I get out of work today and keep you updated.

    Thanks shaggy

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width