Subscript out of range, constant not recognised weirdness. Pls Help! :-(

Davavo

Board Regular
Joined
Aug 3, 2019
Messages
82
hi,
i am out of my depth here. I cold really use some help.
I have cobbled together a macro that (should) look through a column, create new sheets based on the values in that column, copy the sheets to a new workbook with a name chosen by the user, then delete the new sheets on the original.

Each bit of code wotks individually, and I just need to add this code which creates the sheets from the column. It works fine in its own, from both the editor and from the sheet via a button, but when i add it to the rest of the script, i get this runtime out of range error on the constant 'sname'.

I cant understand why it works from the same module with the same sheet in the same workbook when its on its own, but not as part of a larger macro.
(i have tried calleing it, that doesnt work either.)

can anyone see the problem? Much appreciated in advance if you can!

This is the code section....

Code:
Const sname As String = "CCRead" 'change to whatever starting sheetConst s As String = "M" 'change to whatever criterion column
Dim d As Object, a, cc&
Dim p&, i&, rws&, cls&
Set d = CreateObject("scripting.dictionary")
With Sheets(sname)
    rws = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
    cls = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
    cc = .Columns(s).Column
End With
For Each sh In Worksheets
    d(sh.Name) = 1
Next sh


Application.ScreenUpdating = False
With Sheets.Add(after:=Sheets(sname))
Sheets(sname).Cells(1).Resize(rws, cls).Copy .Cells(1)
.Cells(1).Resize(rws, cls).Sort .Cells(cc), 2, Header:=xlYes
a = .Cells(cc).Resize(rws + 1, 1)
p = 2
For i = 2 To rws + 1
    If a(i, 1) <> a(p, 1) Then
        If d(a(p, 1)) <> 1 Then
            Sheets.Add.Name = a(p, 1)
            .Cells(1).Resize(, cls).Copy Cells(1)
            .Cells(p, 1).Resize(i - p, cls).Copy Cells(2, 1)
        End If
        p = i
    End If
Next i
Application.DisplayAlerts = False
    .Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End With
Sheets(sname).Activate

This is the whole thing with the above slotted in

Code:
Sub NewNamedWorkbook()



Dim NewName As String
Dim Swb As Workbook




     
    If MsgBox("Filter range to a new workbook?" _
    , vbYesNo, "NewCopy") = vbNo Then Exit Sub
    
    
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    
    
With Application
               
retry:


         '       Input box to name new file
        NewName = InputBox("Please Specify the name of your new workbook")
        
        
'-------------------------------------------------------------------------------------------


    If StrPtr(NewName) = 0 Then
        MsgBox ("User canceled!")
        GoTo reset
            
    Else
        'MsgBox ("User entered " & NewName)
    End If


       
'------------------------------------------------------------------------------------------


'VBA Check if File Exists
Dim strFile As String
strFile = ThisWorkbook.Path & "\" & NewName & ".xlsx"


'MsgBox "Files would be saved as: " & ThisWorkbook.Path & "\" & NewName & ".xlsx"






If FileExists(strFile) Then
    'File Exists
    MsgBox "The filename you have chosen already exists, please choose a unique filename"
    
    GoTo retry
    
Else


    'File Does Not Exist
   
    
End If
'---------------------------------------------------------------------------------------------


End With




Set NewBook = Workbooks.Add


With NewBook


        .title = NewName 'You can modify this value.
        .Subject = "Expenses In WorkSheets arranged by Cost Centre or Task Code" 'You can modify this value.
        '       Save it with the NewName and in the same directory as the tool


        
        .SaveAs ThisWorkbook.Path & "\" & NewName & ".xlsx"




End With


      
'code here to filter and copy to the named workbook -----------------------------------------------------------------------------------


Const sname As String = "CCRead" 'change to whatever starting sheet
Const s As String = "M" 'change to whatever criterion column
Dim d As Object, a, cc&
Dim p&, i&, rws&, cls&
Set d = CreateObject("scripting.dictionary")
With Sheets(sname)      '<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< error here!!!
    rws = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
    cls = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
    cc = .Columns(s).Column
End With
For Each sh In Worksheets
    d(sh.Name) = 1
Next sh


Application.ScreenUpdating = False
With Sheets.Add(after:=Sheets(sname))
Sheets(sname).Cells(1).Resize(rws, cls).Copy .Cells(1)
.Cells(1).Resize(rws, cls).Sort .Cells(cc), 2, Header:=xlYes
a = .Cells(cc).Resize(rws + 1, 1)
p = 2
For i = 2 To rws + 1
    If a(i, 1) <> a(p, 1) Then
        If d(a(p, 1)) <> 1 Then
            Sheets.Add.Name = a(p, 1)
            .Cells(1).Resize(, cls).Copy Cells(1)
            .Cells(p, 1).Resize(i - p, cls).Copy Cells(2, 1)
        End If
        p = i
    End If
Next i
Application.DisplayAlerts = False
    .Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End With
Sheets(sname).Activate




'---------------------------------------------------------------------------------------------------------------------------------------




    For Each ws In ThisWorkbook.Worksheets
        Select Case ws.Name
            Case "Dashboard", "Expenses", "CCRead", "INVRead"  'list the sheets NOT to copy
            Case Else
            'copy here
                
                With Workbooks("Expenses.xlsm")
                    'ws.Copy After:=.Sheets(.Sheets.Count) 'copys after last sheet
                
                    ws.Copy Before:=Workbooks(NewName & ".xlsx").Sheets(1)
                
                End With
        End Select


    Next




'delete the sheets from the main workbook


    For Each ws In ThisWorkbook.Worksheets
            Select Case ws.Name
                Case "Dashboard", "Expenses", "CCRead", "INVRead"  'list the sheets NOT to copy
                Case Else
                'copy here
                    
                    With Workbooks("Expenses.xlsm")
                        'ws.Copy After:=.Sheets(.Sheets.Count) 'copys after last sheet
                        Application.DisplayAlerts = False
                        ws.Delete
                        Application.DisplayAlerts = True


                    End With
            End Select
    
        Next




  
    Exit Sub


reset:
'Reset Macro Optimization Settings
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True






End Sub
 

Excel Facts

Lock one reference in a formula
Need 1 part of a formula to always point to the same range? use $ signs: $V$2:$Z$99 will always point to V2:Z99, even after copying
Because you haven't specified a workbook it's looking at the active workbook.
So with your code it's looking the "Newbook" for a sheet called "CCRead".
 
Upvote 0
Because you haven't specified a workbook it's looking at the active workbook.
So with your code it's looking the "Newbook" for a sheet called "CCRead".


Hi Fluff, thanks for your response.
I declared the sheet and

I changed that bit of code to

Code:
Set Swb = ThisWorkbookSet Sws = Swb.Sheets("CCRead")


Sheets("CCRead").Activate   'dont know if this is required 


Const sname As String = Sheets("CCRead") 'change to whatever starting sheet
Const s As String = "M" 'change to whatever criterion column
Dim d As Object, a, cc&
Dim p&, i&, rws&, cls&
Set d = CreateObject("scripting.dictionary")

But I am getting "Constant expression required" error now.

I read the microsoft office dev centre page on it but i cant say i am enlightened any.

Could you possibly show me how that should be declared?
 
Last edited:
Upvote 0
Try adding this line to your original code
Code:
[COLOR=#ff0000]ThisWorkbook.Activate[/COLOR]
Const sname As String = "CCRead" 'change to whatever starting sheet
Const s As String = "M" 'change to whatever criterion column
Dim d As Object, a, cc&
Dim p&, i&, rws&, cls&
Set d = CreateObject("scripting.dictionary")
 
Upvote 0
Try adding this line to your original code
Code:
[COLOR=#ff0000]ThisWorkbook.Activate[/COLOR]
Const sname As String = "CCRead" 'change to whatever starting sheet
Const s As String = "M" 'change to whatever criterion column
Dim d As Object, a, cc&
Dim p&, i&, rws&, cls&
Set d = CreateObject("scripting.dictionary")

yay!

Thank you!!

What a relief!

worked with ...

Code:
ThisWorkbook.Activate
Sheets("CCRead").Activate

one day i might have time to figure out why. But for now, thats such a bonus, cant thank you enough!
 
Last edited:
Upvote 0
You're welcome & thanks for the feedback
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,181
Members
453,022
Latest member
Mohamed Magdi Tawfiq Emam

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top