Search code examples
excelvb.netgembox-spreadsheet

VB.NET Gembox - Switch Active Spreadsheet


I've looked all over for this and think I'm just hitting a mental brick wall for something simple. But still. I'm writing a quick program to help me with some mileage spreadsheets for different vehicle. Each vehicle has its on worksheet within the spreadsheet, I'm using GemBox in VB.net.

Basically, dending on which button you press it chooses the correct sheet for the corresponding vehicle. I cannot find anything, anywhere that tells me how to choose a different existing sheet as the active worksheet.

This is my test code atm.

Public Sub SetMiles(vehicle As String)

    Dim wb = ExcelFile.Load(file)
    Dim ws = wb.Worksheets.ActiveWorksheet(vehicle) 

    loc = "F12"
    ws.Cells(loc).Value = "800"


End Sub

Solution

  • In GemBox.Spreadsheet you don't need to set the sheet as active in order to use it.

    In other words, let's say you have an Excel file which has "Sheet1" and "Sheet2". To write into those sheets you can use the following:

    Dim wb = ExcelFile.Load(File)
    
    Dim ws = wb.Worksheets("Sheet1")
    ws.Cells("A1").Value = "Foo"
    
    ws = wb.Worksheets("Sheet2")
    ws.Cells("A1").Value = "Bar"
    

    You can also use the following:

    Dim wb = ExcelFile.Load(File)
    
    Dim ws = wb.Worksheets(0)
    ws.Cells("A1").Value = "Foo"
    
    ws = wb.Worksheets(1)
    ws.Cells("A1").Value = "Bar"
    

    So, I believe that what you need is the following:

    Public Sub SetMiles(vehicle As String)
    
        Dim wb = ExcelFile.Load(File)
        Dim ws = wb.Worksheets(vehicle)
    
        Loc = "F12"
        ws.Cells(Loc).Value = "800"
    
    End Sub
    

    Last, in case you do need to set some sheet as active, then you can do that with GemBox.Spreadsheet as following:

    wb.Worksheets.ActiveWorksheet = wb.Worksheets(vehicle)
    

    However, again GemBox.Spreadsheet doesn't care if the sheet is active or not, you can access and modified it regardless of that. By setting the sheet as active, that sheet will be the first visible one that you see when you open that file in an Excel application.