1

I've referenced this site to answer many of my questions, but this is one I couldn't find an answer to.

Public Sub RemoveBlanks()
Dim Table As ListObject
Set Table = Worksheets("Sheet1").ListObjects("ExampleTable")
Dim r As Range

With Table.DataBodyRange
    For Each r In Table.DataBodyRange
        If r.Value = "" Then r.Value = "-"
    Next r

End With

End Sub

This is the code I used(changed variable/sheet names to generic for ease of conversation).

Declared the variable Dim r As Range But never set a reference or defined what r is. So how does this part work? I thought that for each variable a value or reference had to be assigned for VBA to know what to do with it.

For Each r In Table.DataBodyRange
        If r.Value = "" Then r.Value = "-"
    Next r 

I'm looking for the why.

This is my first post, and I am very green at this programmiing/coding business-Google has been my friend. I'm looking for more theory instead of the good old copy/paste the code in, make a few name changes, and cross my fingers.

My appologies if the formating isn't perfect. I'm happy to clarify if what I'm asking doesn't make sense.

6
  • 1
    For Each r is what performs the assignment - each cell in DatabodyRange is sequentially assigned to r learn.microsoft.com/en-us/office/vba/language/reference/… FYI your With block isn't doing anything here. Commented Mar 9, 2020 at 19:49
  • The For Each r In... bit sets the r variable to the cells in the table, one cell at a time. Commented Mar 9, 2020 at 19:50
  • You may be thinking of something like for i = 1 to 10 that works a little differently than a for each Commented Mar 9, 2020 at 19:50
  • Thanks guys for the quick reply. Yes my goal was for it to look in each cell in the table. Thankfully i found the code on here stackoverflow.com/questions/35746759/… I just didn't understand how r was defined as each cell. @TimWilliams ty for the reference! Commented Mar 9, 2020 at 20:06
  • I would probably write it as For Each r In Table.DataBodyRange.Cells to be more explicit about what the code is doing Commented Mar 9, 2020 at 20:12

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.