开发者

Need macro to cycle through all worksheets

I have the following macro and I need it to perform the same operation on all the worksheets in the workbook, not just the active one. I've tried tons of different stuff, but I don't have much experience with excel so I'm not having mu开发者_JS百科ch luck.

Here's the macro.

Sub Tester()

Dim c As Range, rngMerge As Range

For Each c In ActiveSheet.Range("A1").Resize(1, 100).Cells
    Set rngMerge = c.MergeArea
    If rngMerge.Cells.Count > 1 Then
        c.UnMerge
        rngMerge.Value = rngMerge.Cells(1).Value
    End If
    c.Value = JoinUp(c.Resize(3, 1), "_")
Next c
ActiveSheet.Range("A2:A3").EntireRow.Delete
End Sub


Function JoinUp(rng As Range, Optional Delim As String = "") As String
Dim c As Range, rv As String
For Each c In rng.Cells
    If Len(c.Value) > 0 Then
        rv = rv & IIf(Len(rv) > 0, Delim, "") & c.Value
    End If
Next c
JoinUp = rv
End Function


 Sub ProcessAll()
   Dim sht as worksheet
   for each sht in ActiveWorkbook.Worksheets
      ProcessSheet sht 
   next sht
 End sub


 Sub ProcessSheet(sht as worksheet)

 Dim c As Range, rngMerge As Range

 For Each c In sht.Range("A1").Resize(1, 100).Cells
    Set rngMerge = c.MergeArea
    If rngMerge.Cells.Count > 1 Then
        c.UnMerge
        rngMerge.Value = rngMerge.Cells(1).Value
    End If
    c.Value = JoinUp(c.Resize(3, 1), "_")
 Next c
 sht.Range("A2:A3").EntireRow.Delete
End Sub


Function JoinUp(rng As Range, Optional Delim As String = "") As String
  Dim c As Range, rv As String
  For Each c In rng.Cells
    If Len(c.Value) > 0 Then
        rv = rv & IIf(Len(rv) > 0, Delim, "") & c.Value
    End If
  Next c
  JoinUp = rv
End Function


or use

dim sht as worksheet

for each sht in thisworkbook.sheets
      debug.print sht.name
next sht


To loop over all the sheets in a workbook, you can use:

   dim i as Integer

   For i = 1 To ActiveWorkBook.WorkSheets.Count
       ' do stuff
       ActiveWorkbook.Worksheets(i) ....
   Next i


try:

Sheets(Array("Sheet2", "Sheet1")).Select
Sheets("Sheet2").Activate

or if you want to cycle through:

For Each aSheet In ActiveWorkbook.Sheets
Next aSheet
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜