Save DataGridView to Excel in VB

  • (2 Pages)
  • +
  • 1
  • 2

15 Replies - 761 Views - Last Post: 26 July 2019 - 01:18 PM Rate Topic: -----

#16 modi123_1   User is online

  • Suitor #2
  • member icon



Reputation: 15260
  • View blog
  • Posts: 61,140
  • Joined: 12-June 08

Re: Save DataGridView to Excel in VB

Posted 26 July 2019 - 01:18 PM

MS is pretty upfront on the order of operations to access part of an Excel workbook, and it has been well documented.

Example:

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

        Try
            objApp = New Excel.Application() '-- new app
            objBooks = objApp.Workbooks '-- add collection of workbooks to it.
            objBook = objBooks.Add '-- get a handle to a new book in the collection of books
            objSheets = objBook.Worksheets '-- get a handle to the array of work sheets in the book.
            objSheet = objSheets(1) '-- specific sheet.
            objSheet.Name = "foo" '-- give it a name.

            Dim objRange As Excel.Range = objSheet.Range("A1", "A1") '-- from teh sheet get a range
            objRange.Value = "bar" '-- give the range a value.

            objApp.DisplayAlerts = False

            objBook.SaveAs("C:\test\test3.xlsx") '-- save the book.

            objApp.Quit() '-- release stuff

            objRange = Nothing '-- cleanup
            objSheet = Nothing
            objSheets = Nothing
            objBooks = Nothing
        Catch ex As Exception
            Debug.WriteLine(ex.Message)
            Stop
        End Try

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2