CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Oct 2001
    Posts
    9

    How to open a specific Excel document from VB code ?

    I'm trying to open an Excel document using the Excel9.olb library.
    The following code creates an instance on Excel App:
    Set ExcelSheet = CreateObject("Excel.Sheet")
    But how do I open a specific document (by path and name) without using the "GetObject" function.
    I must use the "CreateObject(...)" before opening the file.
    Thanks !



  2. #2
    Join Date
    Jul 2000
    Location
    Milano, Italy
    Posts
    7,726

    Re: How to open a specific Excel document from VB code ?


    'for example:
    option Explicit

    private Sub Command1_Click()

    Dim xlApp as Object 'Excel.Application 'use as object if you do not put
    'a reference to excel object library.
    'else use Excel.Application and so on
    'Remember: excel should be installed
    'on machine...
    Dim xlWbooks as Object 'Excel.Workbooks
    Dim xlWorkbook as Object 'Excel.Workbook
    Dim xlSheet as Object 'Excel.Worksheet
    Dim intI as Integer

    set xlApp = CreateObject("Excel.Application")
    xlApp.Visible = true 'make it visible only for debugging/showing purpouse
    'you can comment the above line. for testing, put a
    'breakpoint here

    set xlWbooks = xlApp.Workbooks
    xlWbooks.Open "c:\myExcel1.xls" 'path and name to your excel file.
    'Provide a real one!

    for Each xlWorkbook In xlWbooks
    intI = 1
    set xlWorkbook = xlWbooks(intI)
    set xlSheet = xlWorkbook.Worksheets(intI)
    'modify a data
    xlSheet.Cells(1, 1) = "AAA" & intI
    next

    xlApp.DisplayAlerts = false 'do not ask to save /owerwrite
    for Each xlWorkbook In xlWbooks 'and save it
    intI = 1
    set xlWorkbook = xlWbooks(intI)
    xlWorkbook.save
    next
    set xlSheet = nothing 'close and release all referenced object

    set xlWorkbook = nothing

    xlWbooks.Close
    set xlWbooks = nothing
    xlApp.Quit
    set xlApp = nothing
    End Sub





    Special thanks to Lothar "the Great" Haensler, Tom Archer, Chris Eastwood, TCartwright, Bruno Paris, Dr_Michael
    and all the other wonderful people who made and make Codeguru a great place.
    Come back soon, you Gurus.

    The Rater
    ...at present time, using mainly Net 4.0, Vs 2010



    Special thanks to Lothar "the Great" Haensler, Chris Eastwood , dr_Michael, ClearCode, Iouri and
    all the other wonderful people who made and make Codeguru a great place.
    Come back soon, you Gurus.

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

Featured