I am working in VBA and getting data from a database. However, sometimes the data is missing a value. Therefore I want to know when it is missing a value.
I thought I had a clever idea where I could define each column as its own range. Then create an array of those column names, loop through it, then loop through each cell within the range, and then if a cell is empty, take the average of the surrounding cells. However, it doesn't seem like I am defining my "range variable", the variable I use in the first loop through of the columns, correctly. VBA says it is "Nothing."
Dim csheet as Worksheet
Set csheet =ThisWorkbook.Sheets(“Sheet1”)
Dim name1, name2, name3, name4, name5, name6, name7, name8 As Range
Set name1 = csheet.Range("B4", "B25")
Set name2 = csheet.Range("C4", "C25")
Set name3= csheet.Range("D4", "D25")
Set name4= csheet.Range("E4", "E25")
Set name5= csheet.Range("F4", "F25")
Set name6= csheet.Range("G4", "G25")
Set name7= csheet.Range("H4", "H25")
Set name8 = csheet.Range("I4", "I25")
Dim data() As Variant
data = Array(name1, name2, name3, name4, name5, name6, name7, name8)
Dim currentRange As Range
For k = 1 To UBound(data)
currentRange = data(k)
For Each cell In currentRange
If IsEmpty(cell.Value) = True Then
cell.Value = Application.WorksheetFunction.Average(cell.Offset(1, 0).Value, cell.Offset(-1, 0).Value)
If IsError(cell.Value) = True Then
cell.Value = cell.Offset(-1, 0)
ElseIf IsError(cell.Value) = True Then
cell.Value = cell.Offset(1, 0)
ElseIf IsError(cell.Value) = True Then
cell.Value = 0
MsgBox ("There is an error with the data. Please fix once done running. Thank you.")
End If
End If
Next cell
Next