Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a variable for a cell (VBA)

Tags:

excel

vba

I have this code :

If Sheets("CM").Cells(a, b).Value = "" Then
   Sheets("CM").Cells(a, b).Value = shouldBeValue
End If

And I want to refactor it to this one :

c = Sheets("CM").Cells(a, b)
If c.Value = "" Then
   c.Value = shouldBeValue
End If

But I get an error "Expected Object" at the If line, I don't understand why.

like image 268
Robert Vanden Eynde Avatar asked Nov 05 '25 10:11

Robert Vanden Eynde


2 Answers

Creating Object References

  • Set statement
' To create references to objects you need to use the 'Set' keyword.

Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet: Set ws = wb.Worksheets("Sheet1")
Dim cell As Range: Set cell = ws.Cells(a, b)

If Len(CStr(cell.Value)) = 0 Then ' blank i.e. empty, ="", ', ...
'If IsEmpty(cell) Then ' empty
    cell.Value = shouldBeValue
End If
like image 98
VBasic2008 Avatar answered Nov 07 '25 06:11

VBasic2008


Object variables require the Set keyword to be used when assigning their target object:

Set c = Sheets("CM").Cells(a, b)

But you should also consider the advantages of an implicit object reference:

With Sheets("CM").Cells(a, b)
    If .Value = "" Then .Value = shouldBeValue
End With

Using the With statement allows the enclosed code to reference the specified object without further direct reference. In other words, implicitly. In this example, the code makes implicit reference to the Cells(a, b) object twice with .Value. This technique eliminates the need for a separate object variable; it makes the code easier to read and shorter and clearer; and it often executes more quickly than verbose object referencing.

With statements can be nested, but only one can be active at a time.

like image 42
Excel Hero Avatar answered Nov 07 '25 06:11

Excel Hero



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!