Home » excel » vb.net – activate a worksheet by index

vb.net – activate a worksheet by index

Posted by: admin May 14, 2020 Leave a comment


I have a winform with a forward and a backwards button. What I am trying to do is to allow the user to move back and forth on the workbook by clicking on the button. I thought that the best way to achieve this is by using index. However, it is giving me fits. The IDE is telling me that I have syntax errors on lines:

(WS.Index - 1).Activate() 


If Err.Number <> 0 Then WS(1).Activate()

Here is my entire code:

    Option Explicit On
Option Strict On

'Import Libraries
Imports Microsoft.Office.Tools.Excel
Imports System.Drawing
Imports System
Imports System.IO
Imports System.Drawing.Printing
Imports System.Windows.Forms

Public Class frmNavigation

    Dim WB As Excel.Workbook
    Dim WS As Excel.Worksheet

    Private Sub btnMoveBack_Click(sender As Object, e As EventArgs) Handles btnMoveBack.Click

        'This event is triggered when the Previous Sheet button is
        'clicked. The sheet moves to the previous sheet. This event
        'is only run throughout the clientworksheets as the tabs and other
        'standard excel navigation may be disabled.

        WB = CType(Globals.ThisWorkbook.Application.ActiveWorkbook, Excel.Workbook)
        WS = CType(WB.ActiveSheet, Excel.Worksheet)

        WS.Application.ScreenUpdating = False

        On Error Resume Next

       (WS.Index - 1).Activate()                              

        If Err.Number <> 0 Then WS(1).Activate() 'If error stay in the active sheet

        WS.Application.ScreenUpdating = True

    End Sub
How to&Answers:

I think it should be:

WB.WorkSheets(WS.Index -1).Activate()

Instead of just

(WS.Index -1).Activate()