I am trying to assign worksheet reference using a variable integer. To provide context, I imported data, split data into different worksheets based on a date criteria and then name the sheets using the month and year.
I later want to be able to compare data within the different sheets but the trick is I will never know what the date range is until the data is imported. The only differentiation would be the integer variable as I am creating the sheets. Below I have copied parts of the code that relate to my issue.
Dim WS, WS1, WS2, WS3 As Worksheets
Dim Sheetname As String
Dim p, q, y As Integer
p = Worksheets.Count
For q = 1 To p
With Worksheets(q)
Sheetname = Format(st_date, "yyyy-mmm")
ActiveSheet.Name = Sheetname
End With
If q = 1 Then
Set WS1 = ThisWorkbook.Sheets(Sheetname)
End If
If q = 2 Then
Set WS2 = ThisWorkbook.Sheets(Sheetname)
End If
If q = 3 Then
Set WS3 = ThisWorkbook.Sheets(Sheetname)
End If
Next q
When I run the program I get a "type mismatch" error when it has to set WS3. I'm not really sure why it only does that when it gets to 3.
Dim WS, WS1, WS2, WS3 As Worksheetsis an error, you need to Define each object as a worksheet. The correct definition syntax isDim WS As Worksheet, WS1 As Worksheet, WS2 As Worksheet, WS3 As Worksheet. The same goes toDim p, q, y As Integer, - Shai Radost_date, and your With clause is pointless. - SJR