Loop through all worksheets in workbook

前端 未结 3 1749
北海茫月
北海茫月 2020-12-12 02:08

I want to repeat this code on all the worksheets in a workbook.

There may sometimes be 1-2 worksheets sometimes 50+.

Sub HoursTotal()
\'
\' HoursTota         


        
相关标签:
3条回答
  • 2020-12-12 02:42

    You need to activate the worksheet so that excel can make changes to it.

    `Sub HoursTotal() Dim ws As Worksheet

    For Each ws In Worksheets
        ws.Activate
        ws.Range("F2").FormulaR1C1 = "=SUM(C[-1])"
        ws.Range("F1").FormulaR1C1 = "Total Hours"
        ws.Range("G1").Select 'I don't think you need this line but I included it anyways
    Next
    

    End Sub`

    0 讨论(0)
  • 2020-12-12 02:48

    Simple modification of your current code should do it:

    Sub HoursTotal()
    '
    ' HoursTotal Macro
    '
    
    Dim ws as Worksheet
    
    For Each ws in Worksheets
    
        ws.Range("F2").Select
        ActiveCell.FormulaR1C1 = "=SUM(C[-1])"
        ws.Range("F1").Select
        ActiveCell.FormulaR1C1 = "Total Hours"
        ws.Range("G1").Select
    
    Next ws
    
    End Sub
    

    But here's what it looks like without the Select's

    Sub HoursTotal()
    '
    ' HoursTotal Macro
    '
    
    Dim ws as Worksheet
    
    For Each ws in Worksheets
    
        ws.Range("F2").FormulaR1C1 = "=SUM(C[-1])"
        ws.Range("F1").FormulaR1C1 = "Total Hours"
        ws.Range("G1").Select
    
    Next ws
    
    End Sub
    
    0 讨论(0)
  • 2020-12-12 02:52

    This should do it.

    Sub HoursTotal()
        Dim ws As Worksheet
    
        For Each ws In Worksheets
            ws.Range("F2").FormulaR1C1 = "=SUM(C[-1])"
            ws.Range("F1").FormulaR1C1 = "Total Hours"
            ws.Range("G1").Select 'I don't think you need this line but I included it anyways
        Next
    End Sub
    
    0 讨论(0)
提交回复
热议问题