excelvba

Only loop selected rows in Excel VBA


I'm trying to setup a loop that only effects the selected rows. I'm probably just missing something simple but I'm at the point I need a second set of eyes on it.

I'm tying to have it do a simple loop to update column D if Column E is blank within the selected rows. Currently it gives me a type mismatch error.

Basically trying to make this:

enter image description here

Into this:

enter image description here

When I select all the rows for that selection of ID's. I'm assuming I'm missing something simple or my syntax is off a bit. Any help would be greatly appreciated!

My Code currently:

Function pages()
   Dim rng As Range
   Dim lRowSelected As Long
               
   For Each rng In Selection.Rows
      lRowSelected = rng.Row
      If IsNull(ActiveWorkbook.Worksheets(1).Range("D" & rng)) Then
         ActiveWorkbook.Worksheets(1).Range("D" & rng).Value = ActiveWorkbook.Worksheets(1).Range("D" & rng).Value + 1
      End If
   Next rng
        
End Function

Solution

  • Here you're checking for empty cells in Col D - did you mean to check Col E?

    If IsNull(ActiveWorkbook.Worksheets(1).Range("D" & rng)) Then
    

    Something like this is a little simpler:

    Function pages()
       Dim c As Range
       
       For Each c In Selection.EntireRow.Columns("E").Cells
            If Len(c.Value) = 0 Then 
                With c.Offset(0, -1)    'updating Col D...
                    .Value = .Value + 1
                End With
            End If
       Next c
            
    End Function