Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute a function for each cell in a column and loop through all workbooks?

Here's what I have so far:

Sub TrimColumnD()
   Dim ws As Worksheet

   For Each ws In ThisWorkbook.Worksheets
   Dim c As Range
        For Each c In ActiveSheet.UsedRange.Columns("D").Cells
            c.Value = WorksheetFunction.Trim(c.Value)
        Next c
   Next ws

End Sub

The trim function only works on the cells in the first worksheet.

like image 353
user2510323 Avatar asked Jun 21 '13 20:06

user2510323


People also ask

How do you loop through all cells Excel?

Press F5 key to begin looping the column, then the cursor will stop at the first met blank cell.

How do you loop through a cell in a range?

One way to loop through a range is to use the For... Next loop with the Cells property. Using the Cells property, you can substitute the loop counter (or other variables or expressions) for the cell index numbers. In the following example, the variable counter is substituted for the row index.


1 Answers

Please change this line:

For Each c In ActiveSheet.UsedRange.Columns("D").Cells

into this one:

For Each c In ws.UsedRange.Columns("D").Cells

In your code internal loop refers to activesheet while it should refer to ws variable representing sheet.

like image 89
Kazimierz Jawor Avatar answered Oct 11 '22 14:10

Kazimierz Jawor