Im trying to write a code which determines whether certain cells are empty or not and then returns a set string.
To go in detail; I was hoping for the code to look into cell B2, determine if it is empty, then go to C2 and determine if it is non-empty. If both were correct in cell B2 it would then input "Correct" and move on in the range. However, my code doesnt seem to work because it just inputs "Correct" in every cell in the loop range.
I have posted my code below; any help would be much appreciated.
Sub Fill_Rows()
Dim X As Range
Let Y = Range("C2")
For Each X In Range("B2:B5000")
If X = "" And Y <> "" Then
X = "Correct"
End If
Y = Y + 1
Next X
End Sub
If you meant to check by each row like (B2 and C2) then (B3 and C3), then you could do it like this.
Alternative
Added two solutions:
[1] Example Code close to yours
There is no need to use a second variable
Y
, all the more as apparently you left it undeclared, which always can cause issues (type mismatches, no range object etc.). So always useOption Explicit
in the declaration head of your code module to force yourself to declare all variable types you are using.Now you can simply use an offset of 1 column to the existing cell to check the neighbouring cell, too.
[2] Example Code using a datafield array
Looping through a bigger range isn't very fast, you can speed up your procedure by assigning your range values to a variant datafield array
v
, loop through the received array items correcting found items in column 1 and write it back to sheet.Further Notes
ws
)v(1,1)
, in col 2 byv(1,2)
.UBound(v,1)
or even shorter viaUbound(v)
UBound(v,2)
(here the argument 2 is necessary!)vbNullString
can be preferred in coding to""
as it takes less memory (c.f. @PEH 's answer) .