I'm having troubles with my loop. I want to make a worksheet, print it (not build in yet, I know how it works), then delete it. After that proceed to the next j to do the same. But it is relooping the j = 1 to 1, so it's trying to create a second worksheet named "print" and that's not possible.
I have checkboxes with name: CheckBox1, CheckBox2, CheckBox'j'. I want to start with CheckBox1 and end with CheckBox25. If it's true then print the sheet.
I think I need to get rid of the first For:
For Each ctrl In Me.Controls
But I don't know how. Because I need it to specify the variable 'j'.
Private Sub PrintKnop_Click()
Dim ctrl As MSForms.Control
For Each ctrl In Me.Controls
If TypeName(ctrl) = "CheckBox" And Left(ctrl.Name, 8) = "CheckBox" Then
Dim j As Integer
j = Mid(ctrl.Name, 9, 2)
For j = 1 To 1
'it should be possible to adjust the range.
If ctrl.Value = True Then
Dim ws As Worksheet
With ThisWorkbook
Worksheets("Veiligheid").Copy _
before:=ActiveWorkbook.Sheets("Data")
Set ws = ActiveSheet
ws.Name = "print"
End With
'Application.DisplayAlerts = False
'Sheets("print").Delete
'Application.DisplayAlerts = True
'These shouldn't be comments, but if I uncomment it, it won't show the failures.
End If
Next
For j = 2 To 4
If ctrl.Value = True Then
With ThisWorkbook
Worksheets("Veiligheid").Copy _
before:=ActiveWorkbook.Sheets("Data")
Set ws = ActiveSheet
ws.Name = "printen"
End With
'Application.DisplayAlerts = False
'Sheets("printen").Delete
'Application.DisplayAlerts = True
End If
Next
End If
Next
End Sub
j = Mid(ctrl.Name, 9, 2)if the very next line is usingjas the index of a for loop? In any eventFor j = 1 To 1will only run once, but it is embedded in a larger loop which can presumably run multiple times. I find the question quite unclear. If you want code to run only once, don't put it in a loop.