Link to home
Start Free TrialLog in
Avatar of Sandra Smith
Sandra SmithFlag for United States of America

asked on

Subscript out of range when trying to set worksheet variable

i have the below which sometimes work and sometimes does not.  It stops at the Set wks line.  This module is in an ACCESS 2003 database opening the Excel workbook.

Sandra

Option Explicit
'Daily upload of debits and credits from accounting
Const strPath = "\\Sf1\User1\shared\EFT\ATM\Private\Backend\ATMUpload.xls" 'Path to directory
Const strTab = "Cumulative Journal Transaction " 'Name of data source tab
Const strWKBName = "ATMUpload.xls"
Public Sub DefineDataRange()
On Error GoTo ErrorHandler
'Late Binding (Needs no reference set)
    Dim objExcel As Object
    Dim wks As Worksheet
    Dim wkb As Workbook
    Dim intRow As Integer
    Dim rngDataSource As Range
   
     '   Create a new Excel instance
    Set objExcel = CreateObject("Excel.Application")
     
     '   Open it
    With objExcel
        .Visible = True
        .Workbooks.Open (strPath)
        .Workbooks(strWKBName).Activate
        .Workbooks(strWKBName).Worksheets(strTab).Select
       
 'SOMETIMES RUNS SOMETIMES DOESN'T-Subscript out of range error
Set wks = Workbooks(strWKBName).Worksheets(strTab)
    End With
   
    With wks
        .Range("A5").Activate
        intRow = .Range("A200").End(xlUp).Row
    Set rngDataSource = Range("A5", "G" & intRow)
        rngDataSource.Name = "DataSource"
    End With
   
    Workbooks(strWKBName).Close SaveChanges:=True
     
Exit_ErrorHandler:
    Set objExcel = Nothing
    Exit Sub
     
ErrorHandler:
    objExcel.Visible = False
    MsgBox "Error Number: " & Err.Number & vbCrLf & _
           "Description: " & Err.Description
    Resume Exit_ErrorHandler
End Sub
ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
try this coding

Set objExcel = CreateObject("Excel.Application")
     
     '   Open it
      objExcel.Workbooks.Open (strPath)
    With objExcel
        .Visible = True
       
        .Activate
        .Worksheets(strTab).Select
       
           Set wks = .Worksheets(strTab)
    End With
Avatar of Sandra Smith

ASKER

I got a variations of this to work.  Capricon, I did try what you indicated prior to posting the question, but I could not get it to work.  Thank you both.

Sandra
imnoie, this is what I changed, the objWB was not set (typo, happens)

    '   Open it
    With objExcel
        .Visible = True
        Set objWB = .Workbooks.Open(strPath)
    End With
Avatar of Norie
Norie

Oops, don't know how I missed that out.