VBA set cell value after .ClearContents

872 Views Asked by At

Why does the cell value not set in another function when clearing the contents of the range in another function?

I'm trying to set a cell value to "All" after clearing the cells in the range. I've even tried to get a message box to pop up to see if i can somehow check if my check value is correct.

DelRange is the range i'm clearing.

Building is the cell that i'm checking the value for and if it's blank, it needs to change to "All".

clearPreviw is used to clear another sheet, which it's doing.

Sub ClearSheet()

Dim Dash As Worksheet
Dim DelRange As Range
Dim Building As Range
Set Dash = ActiveWorkbook.Worksheets("DASH")
Set DelRange = Dash.Range("FilterData")
Set Building = Dash.Range("SelBuild")

  DelRange.ClearContents
  Call clearPreview

 'This part below doesn't work when the Range.ClearContents has been done, but doing it on it's own without clearing the range works fine
  If Building.Value = "" Then
        MsgBox "Building is empty", vbOKOnly
        Building.Value = "All"
  End If

End Sub

I've run this test as a separate process which works, but once again when running it as a call function right after .ClearContents seems to stop this.

Sub test()

Dim Dash As Worksheet
Dim DelRange As Range
Dim Building As Range
Set Dash = ActiveWorkbook.Worksheets("DASH")
Set DelRange = Dash.Range("FilterData")
Set Building = Dash.Range("SelBuild")

    If Building.Value = "" Then
        MsgBox "Building is empty", vbOKOnly
        Building.Value = "All"
    End If

End Sub

I've been poking at it and searching but i can't wrap my head around this.

2

There are 2 best solutions below

2
On BEST ANSWER

I think you are missing:

Building.ClearContents;

Also I would prefer:

If IsEmpty(Building.Value) Then

over:

If Building.Value = "" Then
1
On

This link gives you a good start on how to set range variables (although I would advice you against the use of .Select and .Activate).

After that, use .ClearContents or .Clear, depending on your needs.

If you properly cleared the ranges, there is no need to check if they are empty, so this might be a redundant step within your current planning.