I'm having some trouble getting to grips with using/calling variables and other sub routines. I thought I'd use the following bits of code as an example of what I currently have and with your help how you think it SHOULD read.
Private Sub CommandButtonOut_Click()
' Check Selected Cell is one that can be changed
If Intersect(ActiveCell, Range("C5:L5,C10:L10,C15:L15,C20:L20,C25:L25,C30:L30,C35:L35,C40:L40,C51:L51,C57:E57")) Is Nothing Then
MsgBox ("You must select a white cell with a name in it!")
Else
Sheet1.Unprotect Password:="password"
If ActiveCell = Range("A3") Then
Selection.Interior.ColorIndex = xlNone
Range("A3").Select
Else
With Selection.Interior
.ColorIndex = 3
.Pattern = xlSolid
End With
Range("A3").Select
Sheet1.Protect Password:="password"
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
, AllowFormattingCells:=True
ActiveSheet.EnableSelection = xlNoRestrictions
ActiveWorkbook.Save
End If
End If
End Sub
Private Sub CommandButtonMeeting_Click()
' Check Selected Cell is one that can be changed
If Intersect(ActiveCell, Range("C5:L5,C10:L10,C15:L15,C20:L20,C25:L25,C30:L30,C35:L35,C40:L40,C51:L51,C57:E57")) Is Nothing Then
MsgBox ("You must select a white cell with a name in it!")
Else
Sheet1.Unprotect Password:="password"
If ActiveCell = Range("A3") Then
Selection.Interior.ColorIndex = xlNone
Range("A3").Select
Else
With Selection.Interior
.ColorIndex = 41
.Pattern = xlSolid
End With
Range("A3").Select
Sheet1.Protect Password:="password"
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
, AllowFormattingCells:=True
ActiveSheet.EnableSelection = xlNoRestrictions
ActiveWorkbook.Save
End If
End If
End Sub
As you will no doubt guess each Private Sub is attached to a command button, when you click the button it checks to see if the selected cell is within a range and if it is changes it's colour. There are more than 2 buttons in total by the way, I've just using 2 as an example (hence my desire to write tighter code).
The only code difference in the routines is the colour that the cell is changed to, so it would make sense to use variables but I'm falling down at this point as to how to declare them. Also you'll notice the range that the function checks is the same, again a variable for this seems logical called from outside the routine this time?
The way I would expect the whole thing to work is have 1 sub routine written elsewhere that's called when the command button is clicked. The colours would be a variable at the start too. I'm thinking something along the lines of the following (naturally the code is just a concept):
Sub Click1 ()
Dim Colour = 1
ChangeColour
End Sub
Sub Click2 ()
Dim Colour = 2
ChangeColour
End Sub
Sub ChangeColour ()
Codehere
End Sub
If anyone can spare the time to show me how to improve this code I'd be grateful.
Thanks in advance.
Brelin
Bookmarks