1

I'm having an issue with my For If statement. The scenario is that, I need the empty cells to be filled with a telephone number. I have made a code and it works but at some point it will stop in between. Sometimes all the way to the end of the last row or just skip a few cells and continue again. I'm really not sure about this weird issue, hopefully someone can give me an insight. I have also attached a snapshot of the results.

My code is as shown below:-

    Dim pn As Range
    Dim h As Integer, phone As Integer
    lastrow = Range("A" & Rows.Count).End(xlUp).Row
    
    Set pn = Range("AE2:AE" & lastrow)
    h = 1

    For phone = 1 To pn.Rows.Count
       If pn.Cells(h) = "" Then
         pn.Cells(h) = "03-33422828"
       Else
         h = h + 1
       End If
    Next

enter image description here

3
  • 1
    Get rid of all the h lines and use pn.Cells(phone). Commented Aug 3, 2021 at 16:08
  • Gosh! All this time my understanding on the For If statement implementation has been a bit wrong.. Thanks a lot BigBen! It worked accordingly :D Commented Aug 3, 2021 at 17:05
  • 1
    Even better, Dim cell As Range, For Each cell in pn, If cell.Value = "" Then, cell.Value = "03-33422828", End If. Commented Aug 3, 2021 at 17:06

1 Answer 1

2

An alternative way to do this is to select all the used cells in that range, then fill all the blank ones with a value.

For example, if we have a workbook with data in column A and we want to fill the blank cells in that column with "---" we could do this:

On Error Resume Next
Range("A1:A" & ActiveSheet.UsedRange.Rows.Count). _
  SpecialCells(xlCellTypeBlanks).Value = "---"
On Error GoTo 0

VBA will generate an error if there are no blank cells, so I've "handled" that by just ignoring any errors.

Before & After

For you it would be more like:

On Error Resume Next
Range("AE1:AE" & ActiveSheet.UsedRange.Rows.Count). _
  SpecialCells(xlCellTypeBlanks).Value = "03-33422828"
On Error GoTo 0
Sign up to request clarification or add additional context in comments.

1 Comment

Hey there Robson. This is actually a good alternative way, shorter way too! I've tried it and will also definitely implement this method in future. Thank you very much mate! :D

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.