Results 1 to 17 of 17

Thread: [Excel] Writing a macro to set alternate background colors in rows?

  1. #1

    Thread Starter
    Banned timeshifter's Avatar
    Join Date
    Mar 2004
    Location
    at my desk
    Posts
    2,465

    [Excel] Writing a macro to set alternate background colors in rows?

    I'm a complete and utter Excel n00b, so pardon my ignorance... I've written a few macros for Visual Studio, so I kinda get the idea. Essentially, I want to do exactly what the title says: select a whole bunch of cells, and run a macro that puts a light gray background color to every other row. Not knowing anything about how Excel works, I'm honestly not even sure where to start...

  2. #2
    Junior Member Akos_beres's Avatar
    Join Date
    Mar 2009
    Location
    Minneapolis, MN
    Posts
    24

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    Which version of excel ... approximately how many rows do you need to format? Do you want to format the entire row or maybe rows within a range.

  3. #3
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    Hi Time shifter... It is very easy to record a macro in excel... I am assuming that you are using excel 2003

    Open Excel, Click on Menu->Tool->Macros->Record New macro to start the macro and simply perform the task that you want to do...

    Once done stop the macro and press Alt+F11 to amend the macro in the module...

    If you have any questions do ask...
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  4. #4
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    Actually, Sid, I already did that.

    I didn't post it yet, because I am having a problem. This is what the macro gave me.
    Code:
    Sub Macro1()
    '
    ' Macro1 Macro
    ' Macro recorded 3/25/2009 by Hack
    '
    
    '
        Rows("1:1").Select
        With Selection.Interior
            .ColorIndex = 15
            .Pattern = xlSolid
        End With
        Rows("3:3").Select
         With Selection.Interior
            .ColorIndex = 15
            .Pattern = xlSolid
        End With
        Rows("5:5").Select
         With Selection.Interior
            .ColorIndex = 15
            .Pattern = xlSolid
        End With
    End Sub
    Now, what I'm trying to do, and failing it, is replacing Rows("3:3") with a variable like i
    Code:
    For i = 1 To 264
        Sheets("sheet1").Rows("i:i").Select
        With Selection.Interior
            .ColorIndex = 15
            .Pattern = xlSolid
        End With
    Next
    Everything I've tried to replace the hard code numbers has come up with an error. I've tried a wide variety of things, not just the ("i:i") thing.

  5. #5
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    vb Code:
    1. Sub test()
    2.     For i = 1 To 264
    3.         Sheets("sheet1").Rows(i).Select
    4.         With Selection.Interior
    5.             .ColorIndex = 15
    6.             .Pattern = xlSolid
    7.         End With
    8.     Next
    9. End Sub

    The i is treated as a variable once you put it in quotes...
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  6. #6
    I'm about to be a PowerPoster! Hack's Avatar
    Join Date
    Aug 2001
    Location
    Searching for mendhak
    Posts
    58,333

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    I almost said "Thank you sir" except this isn't my thread or my question.

    However, I'm sure that when TimeShifter comes along, he will say so himself.

  7. #7
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    @Time Shifter: You can use "Step" in the loop to color alternate rows...

    something like

    vb Code:
    1. Sub ColorRows()
    2.     '~~> This will color alternate rows starting
    3.     '~~> from row 1 and up till Row 50
    4.     For i = 1 To 50 Step 2
    5.         Sheets("sheet1").Rows(i).Select
    6.         With Selection.Interior
    7.             .ColorIndex = 15
    8.             .Pattern = xlSolid
    9.         End With
    10.     Next
    11. End Sub
    Last edited by Siddharth Rout; Mar 25th, 2009 at 12:32 PM.
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  8. #8

    Thread Starter
    Banned timeshifter's Avatar
    Join Date
    Mar 2004
    Location
    at my desk
    Posts
    2,465

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    Sorry for my delayed response... had to run out of the office for a bit, then enjoy my chicken & sausage gumbo

    @Akos_beres: Excel 2007, any feasible number (we'll likely be dealing with reports a lot, so possibly thousands of rows at a time), and whatever the user has selected.

    @Hack: You have my permission to say thank you

    @sid: The goal is to let the user select what they need formatted and run with that... Your code certainly looks simple enough, which I like, but what about the dynamic side of it? How would it handle only formatting alternating rows in a selection?

  9. #9
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    @sid: The goal is to let the user select what they need formatted and run with that... Your code certainly looks simple enough, which I like, but what about the dynamic side of it? How would it handle only formatting alternating rows in a selection?
    Gimme a quick moment and I will give the code for that as well

    Edit:

    vb Code:
    1. Sub ColorRows()
    2.     Dim i As Long, StartRow As Long, EndRow As Long
    3.    
    4.     '~~> Ask the user for the start Row
    5.     StartRow = InputBox("Please enter the starting row:")
    6.     '~~> Ask the user for the last Row
    7.     EndRow = InputBox("Please enter the Last row:")
    8.    
    9.     '~~> This will color alternate rows starting
    10.     '~~> from rStartRow and up till EndRow
    11.     For i = StartRow To EndRow Step 2
    12.         Sheets("sheet1").Rows(i).Select
    13.         With Selection.Interior
    14.             .ColorIndex = 15
    15.             .Pattern = xlSolid
    16.         End With
    17.     Next
    18. End Sub
    Last edited by Siddharth Rout; Mar 25th, 2009 at 12:42 PM.
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  10. #10

    Thread Starter
    Banned timeshifter's Avatar
    Join Date
    Mar 2004
    Location
    at my desk
    Posts
    2,465

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    That still requires the user to know what rows they want to highlight... Yes, I get the idea, but my goal was to have it be based on whatever cells are currently highlighted. VS macros have this:
    VB Code:
    1. Dim selection As EnvDTE.TextSelection = ActiveDocument.Selection
    2. Dim text As String = selection.Text
    to retrieve the selection. How would one do the Excel equivalent?

  11. #11
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    Quote Originally Posted by timeshifter View Post
    That still requires the user to know what rows they want to highlight... Yes, I get the idea, but my goal was to have it be based on whatever cells are currently highlighted. VS macros have this:
    VB Code:
    1. Dim selection As EnvDTE.TextSelection = ActiveDocument.Selection
    2. Dim text As String = selection.Text
    to retrieve the selection. How would one do the Excel equivalent?
    Ok how about this...

    the user will make a selection and then run this macro.... It will color alternate rows in the selection made by the user...

    vb Code:
    1. Sub ColorRows()
    2.     Dim pos1 As Long, pos2 As Long
    3.     Dim Addr As String
    4.     Dim StartRow As Long, EndRow As Long
    5.    
    6.     '~~> Get the adress of the selected range
    7.     '~~> will be of the format $1:$10
    8.     Addr = Selection.Address
    9.    
    10.     '~~> Locate the first "$"
    11.     pos1 = InStr(1, Addr, "$")
    12.    
    13.     '~~> Locate the ":"
    14.     pos2 = InStr(1, Addr, ":")
    15.    
    16.     '~~> Get Startrow
    17.     StartRow = Mid(Addr, pos1 + 1, pos2 - pos1 - 1)
    18.    
    19.     '~~> Get Endrow
    20.     EndRow = Mid(Addr, pos2 + 2, Len(Addr) - pos2)
    21.    
    22.     '~~> This will color alternate rows starting
    23.     '~~> from StartRow and up till EndRow
    24.     For i = StartRow To EndRow Step 2
    25.         Sheets("sheet1").Rows(i).Select
    26.         With Selection.Interior
    27.             .ColorIndex = 15
    28.             .Pattern = xlSolid
    29.         End With
    30.     Next
    31. End Sub

    Hope this is what you wanted?
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  12. #12

    Thread Starter
    Banned timeshifter's Avatar
    Join Date
    Mar 2004
    Location
    at my desk
    Posts
    2,465

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    First try kinda threw an error... I'll go in and try to debug it later. Getting the selection is the tricky part... from there, it should just be brushing up on VBA a little bit... which I'm moderately familiar with, from writing macros for VS. Thanks for the start, though

  13. #13
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    What error did you get?
    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  14. #14
    Head Hunted anhn's Avatar
    Join Date
    Aug 2007
    Location
    Australia
    Posts
    3,669

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    Another way is to use Conditional formatting, that can be set manually or by code:
    Code:
       Selection.FormatConditions.Delete
       Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=MOD(ROW(),2)=0"
       Selection.FormatConditions(1).Interior.ColorIndex = 15
    • Don't forget to use [CODE]your code here[/CODE] when posting code
    • If your question was answered please use Thread Tools to mark your thread [RESOLVED]
    • Don't forget to RATE helpful posts

    • Baby Steps a guided tour
    • IsDigits() and IsNumber() functions • Wichmann-Hill Random() function • >> and << functions for VB • CopyFileByChunk

  15. #15

    Thread Starter
    Banned timeshifter's Avatar
    Join Date
    Mar 2004
    Location
    at my desk
    Posts
    2,465

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    I tried something that claimed to be conditional formatting, with little success... maybe I'm just too much of an Excel n00b to know how to properly use the tools it has...

  16. #16
    Discovering Life Siddharth Rout's Avatar
    Join Date
    Feb 2005
    Location
    Mumbai, India
    Posts
    12,001

    Re: [Excel] Writing a macro to set alternate background colors in rows?

    A good exercise for the Heart is to bend down and help another up...
    Please Mark your Thread "Resolved", if the query is solved


    MyGear:
    ★ CPU ★ Ryzen 5 5800X
    ★ GPU ★ NVIDIA GeForce RTX 3080 TI Founder Edition
    ★ RAM ★ G. Skill Trident Z RGB 32GB 3600MHz
    ★ MB ★ ASUS TUF GAMING X570 (WI-FI) ATX Gaming
    ★ Storage ★ SSD SB-ROCKET-1TB + SEAGATE 2TB Barracuda IHD
    ★ Cooling ★ NOCTUA NH-D15 CHROMAX BLACK 140mm + 10 of Noctua NF-F12 PWM
    ★ PSU ★ ANTEC HCG-1000-EXTREME 1000 Watt 80 Plus Gold Fully Modular PSU
    ★ Case ★ LIAN LI PC-O11 DYNAMIC XL ROG (BLACK) (G99.O11DXL-X)
    ★ Monitor ★ LG Ultragear 27" 240Hz Gaming Monitor
    ★ Keyboard ★ TVS Electronics Gold Keyboard
    ★ Mouse ★ Logitech G502 Hero

  17. #17
    Head Hunted anhn's Avatar
    Join Date
    Aug 2007
    Location
    Australia
    Posts
    3,669

    [Excel] Macro to set alternate background colors in rows

    Do you think this post should be in CodeBank?

    1. Method 1: Hard-color alternate rows
    This code will need to be re-run if later a row will be inserted or deleted within the range.
    Code:
    Sub AlternateRowColors(Optional aRange As Range, _
                           Optional BG0 As Long = 19, _
                           Optional BG1 As Long = 20)
       Dim BG As Variant, Area As Range, r As Long
    
       BG = Array(BG0, BG1) ' use 2 colorindex of your choices
       If aRange Is Nothing Then Set aRange = Selection
       '-- we need to use Areas because aRange or Selection may consist of
       '-- more than one areas, otherwise only the first area will be colored
       For Each Area In aRange.Areas
          For r = 1 To Area.Rows.Count
             Area.Rows(r).Interior.ColorIndex = BG(r Mod 2)
          Next
       Next
    End Sub
    Code:
    Sub UsageExamples()
    '-- Clear all interior color
       [A1:K20].Interior.ColorIndex = xlNone
       
    '-- Example 1:
       [A4:C10].Select
       AlternateRowColors
       MsgBox "[A4:C10] was selected and colored as default"
       
    '-- Example 2:
       [B6:E12].Select
       AlternateRowColors , 15, xlNone
       MsgBox "[B6:E12] was selected and colored with my choices"
    
    '-- Example 3:
       AlternateRowColors [H1:K20]
       MsgBox "[H1:K20] was colored as default without selected"
    
    '-- Example 4:
       AlternateRowColors [A1:D10,D8:F15], 18, 23
       MsgBox "2 Areas [A1:D10] and [D8:F15] was colored with my choices"
       
       Range("A1").Select
       
    End Sub
    2. Method 2: Use Conditional Formating to color alternate rows
    The advantage of Conditional formatting method here is when you insert a new row or delete a row within the range then you don't need to re-run the code, the colors will be auto adjusted.
    Code:
    Sub ConditionalAltRowColors()
       '-- No need to use areas here even the Selection consist of more than one areas.
       '-- You can replace Selection with any range of your choices.
       With Selection.FormatConditions
          .Delete
          .Add Type:=xlExpression, Formula1:="=MOD(ROW(),2)=0"
          .Item(1).Interior.ColorIndex = 19
          .Add Type:=xlExpression, Formula1:="=MOD(ROW(),2)=1"
          .Item(2).Interior.ColorIndex = 20
       End With
    End Sub
    PS.
    No need to say thanks to my code if it works for you, but if it is used then it should be credited.
    Rows(i) instead of Rows(i & ":" & i) was what I taught someone when he was still young.
    • Don't forget to use [CODE]your code here[/CODE] when posting code
    • If your question was answered please use Thread Tools to mark your thread [RESOLVED]
    • Don't forget to RATE helpful posts

    • Baby Steps a guided tour
    • IsDigits() and IsNumber() functions • Wichmann-Hill Random() function • >> and << functions for VB • CopyFileByChunk

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width