PDA

View Full Version : Shorten VBA Code By Removing Redundant Superfluous Code



paul_pearson
08-15-2013, 01:34 AM
hI

This code below i have modified to get it to work...it does work but could it be made simpler or tidied up




Option Explicit

Sub SubTotalize()

With Sheets("XFLOW A")
.Unprotect Password:="abc"
.Range("B3:H" & .Cells(Rows.Count, 2).End(xlUp).Row).Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(2, 3, 7), Replace:=True, PageBreaks:=False, SummaryBelowData:=True
.Protect UserInterfaceOnly:=True, Password:="abc"
End With
End Sub
Sub Subtotalize_1()
With Sheets("XFLOW B")
.Unprotect Password:="abc"
.Range("B3:H" & .Cells(Rows.Count, 2).End(xlUp).Row).Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(2, 3, 7), Replace:=True, PageBreaks:=False, SummaryBelowData:=True
.Protect UserInterfaceOnly:=True, Password:="abc"
End With
End Sub
Sub subtotalize_2()
With Sheets("XFLOW C")
.Unprotect Password:="abc"
.Range("B3:H" & .Cells(Rows.Count, 2).End(xlUp).Row).Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(2, 3, 7), Replace:=True, PageBreaks:=False, SummaryBelowData:=True
.Protect UserInterfaceOnly:=True, Password:="abc"
End With
End Sub

Excel Fox
08-15-2013, 12:23 PM
This could be one way to shorten it



Sub SubTotalize()

Dim var, strarrSheetNames() As String
strarrSheetNames = Split("XFLOW A,XFLOW B,XFLOW C", ",")
For Each var In strarrSheetNames
With Sheets(var)
.Unprotect Password:="abc"
.Range("B3:H" & .Cells(Rows.Count, 2).End(xlUp).Row).Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(2, 3, 7), Replace:=True, PageBreaks:=False, SummaryBelowData:=True
.Protect UserInterfaceOnly:=True, Password:="abc"
End With
Next var

End Sub

paul_pearson
08-15-2013, 09:09 PM
Thank you

I still have an error when I select Daily Total button on XFLOW A sheet.It still performs the totals but pops up a error message.I think the error could be that both XFLOW B & C sheets are empty of data.
On the attached sample if the Daily Total button is pressed it will show the error.
Can the sheets all have the Daily Total option but work independent of each other.Example would be that XFLOW A & B might get data daily but XFLOW C may get data every second or third day..

Thanks

Paul