Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 207
  • Last Modified:

VBA code issue refernce to worksheet

Hi all,

I am getting a (subscript out of range) error with the following code and despite my best efforts, cannot seem to work out what is causing it.

I am wanting to ensure I reference the actual Sheet Number of the workbook so that if someone changes the sheetname, the code will not bug out.

Dim wkb As Workbook
    Dim wks1 As Worksheet
    Dim wks2 As Worksheet
    Dim rng As Range
    
    Set wkb = Application.ThisWorkbook
          
    'turn off updates to speed up code execution ->
    With Application
        .ScreenUpdating = False
        .EnableEvents = False
        .Calculation = xlCalculationManual
        .DisplayAlerts = False
    End With
           
    Set wks1 = wkb.Sheets("Sheet9") 
    Set wks2 = wkb.Sheets(Sheet17) 

Open in new window


Any ideas?

TA
0
discogs
Asked:
discogs
  • 3
  • 2
  • 2
  • +1
2 Solutions
 
Rgonzo1971Commented:
HI
with ""
Set wks2 = wkb.Sheets("Sheet17")  

Open in new window

Regards
0
 
Saqib Husain, SyedEngineerCommented:
Set wks2 = wkb.Sheets("Sheet17")
0
 
discogsAuthor Commented:
Errors on both guys. Subscript out of range...
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Saqib Husain, SyedEngineerCommented:
Do you have a sheet whose name is displayed as Sheet17?

Is this the line which is giving an error?
0
 
Rgonzo1971Commented:
Hi,

pls try fuirst select the wbk
 
Set wks2 = Sheet17

Open in new window

Regards
0
 
Pratima PharandeCommented:
yes you can  reference the actual Sheet Number of the workbook  like below ,
Try giving your numbers , I tried like below and working fine

 Set wks1 = wkb.Sheets(1)
    MsgBox (wks1.Name)
    Set wks2 = wkb.Sheets(2)
    MsgBox (wks2.Name)
0
 
Rgonzo1971Commented:
Hi,

Or you could use a function to find the name of the sheet

Function fNameOfSheet(Wb As Workbook, CodeName As String) As String
    fNameOfSheet = Wb.VBProject.VBComponents(CodeName).Properties("Name").Value
End Function

Open in new window


Dim wkb As Workbook ' do not forget to declare
Set wks2 = wkb.Sheets(fNameOfSheet(wkb, "Sheet17"))

Open in new window

Regards
0
 
discogsAuthor Commented:
Great stuff guys. It works. Both solutions split 50/50 as they both worked for me. Thanks
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now