Replace Blank/empty cell with a string value

自闭症网瘾萝莉.ら 提交于 2020-07-18 21:05:58

问题


Hope someone can help. I need to populate any blank/empty cells within a range of cells with a specific string. I also don't know that the last row would be in that range so I am looking for that first, I know that line of code works as I have used it for another function within the script. Below is the code I am using: -

    LastRow = Cells(Rows.Count, 2).End(xlUp).Row

    For Each r In Range("AS22:AU" & LastRow)
        If r.Value2 = vbNullString Then
            r.Value2 = "Greens"
        End If
    Next

I don't seem to get any compile errors when I run the code, it just does not work, I still have the same blank/empty cells.

Can anyone shed any light onto what I am doing wrong?


回答1:


You could just use the .Replace Method with the range. It would be much quicker.

Range("AS22:AU" & LastRow).Replace "", "Greens", xlWhole



回答2:


How about:

Sub dural()
    Dim r As Range, LastRow As Long

    LastRow = Cells(Rows.Count, 2).End(xlUp).Row
    For Each r In Range("AS22:AU" & LastRow)
        If r.Text = "" Then r.Value = "Greens"
    Next r
End Sub

This will change:

  • truly empty cells
  • cells containing formulas returning Null
  • cells containing Null character as a constant



回答3:


Use IsEmpty() to test for blanks.

    If IsEmpty(r.Value2) Or Trim(r.Value2) = "" Then
        r.Value2 = "Greens"
    End If

Also watch out for cells with a zero length string or a space. They appear empty but in fact are not.



来源:https://stackoverflow.com/questions/35746759/replace-blank-empty-cell-with-a-string-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!