简体   繁体   中英

excel VBA Looping through worksheets : ActiveWorkbook.Worksheets(I)?

Yesterday I decided to learn some VBA to make my excel time easier. It has been going better then expected, but I have been breaking my teeth on this code for many hours now.

I am trying to remove all empty (except title) columns, and this in all sheets of a workbook. After lots of googling I managed to find some examples i could adapt to my needs.

I used this code: remove columns and then tried to loop it through the sheets by using dear old microsoft support

Together i frankensteined it into this:

Sub WorksheetLoop()

Dim WS_Count As Integer
Dim I As Integer
Dim MyRange As Range
Dim iCounter As Long

 WS_Count = ActiveWorkbook.Worksheets.Count
 For I = 1 To WS_Count

'removecode

    ' Define the target Range.
      Set MyRange = ActiveWorkbook.Worksheets(I).UsedRange

    'Start reverse looping through the range.
     For iCounter = MyRange.Columns.Count To 1 Step -1

    'If entire column is empty then delete it.
    If Application.CountA(Columns(iCounter).EntireColumn) = 1 Then
     Columns(iCounter).Delete
    End If

    Next iCounter

'endremovecode

      MsgBox ActiveWorkbook.Worksheets(I).Name

     Next I

  End Sub

When I run this, only the the starting worksheet is cleaned up. The messagebox does loop through all of them.

Why? What am I doing wrong? I tried finding a solution, but non of the topics here seemed to give more clarity.

Thank a bunch for leading me in the right direction.

Lara

Columns(iCounter).EntireColumn

and

Columns(iCounter).Delete

are not prefixed with MyRange so refer to the active sheet's columns not the sheet containing MyRange . Stick MyRange. infront of them.

You're almost there. You just need to qualify your application.counta and also your .columns().delete. so each is working directly with the sheet in question. Otherwise it's just working with the active sheet.

Try this:

Sub WorksheetLoop()

Dim WS_Count As Integer
Dim I As Integer
Dim MyRange As Range
Dim iCounter As Long
Dim ws As Worksheet

 WS_Count = ActiveWorkbook.Worksheets.Count

 For I = 1 To WS_Count
    Set ws = ActiveWorkbook.Worksheets(I)
    'removecode

    With ws
    ' Define the target Range.
      Set MyRange = .UsedRange

        'Start reverse looping through the range.
         For iCounter = MyRange.Columns.Count To 1 Step -1

            'If entire column is empty then delete it.
            If Application.CountA(.Columns(iCounter).EntireColumn) = 0 Then
             .Columns(iCounter).Delete
            End If

        Next iCounter
    End With

'endremovecode

      MsgBox ws.Name

     Next I

  End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM