How to check if a value of an array is empty

Viewed 101

I am writing a chess program and has to see whether certain value are empty. I tried

aPiece is an array of CommandButtons. cmdSquare is a control array of shapes.

Private aPiece(63) As CommandButton

...

For p = 0 To 63
    If IsEmpty(aPiece(p)) Then
        aPiece(p).Left = cmdSquare(p).Left
        aPiece(p).Top = cmdSquare(p).Top
    
    End If
Next p 

All variable are declared and is seem to be IsEmpty function which is not working.

2 Answers

The IsEmpty method only returns meaningful information for variants. Since the array contains objects, you need to check like this:

If aPiece(p) Is Nothing Then

However, this seems like only part of the answer. The above logic is saying "If there is no piece in my array then update it's location". That doesn't make sense to me and will generate an error. You also need to add Not like below:

For p = 0 To 1
   If Not aPiece(p) Is Nothing Then
      aPiece(p).Left = cmdSquare(p).Left
      aPiece(p).Top = cmdSquare(p).Top
   End If
Next p

It depends on the datatype of aPiece. If it is a variant and you haven't assigned a value to it, IsEmpty will return true. However, if it is a String, Date, Integer, etc. those are automatically initialized (String will be an empty string, Integer will be 0) so IsEmpty will return false.

A pretty good reference is this page: IsEmpty Function - Visual Basic 6.0

Related