简体   繁体   中英

Out of Range error in Excel VBA when trying to access array element that doesn't exist

I have a very basic problem.

Context: 1) I have a column where each cell may or may not contain a list of comma separated entries. 2) I loop through each row and split each cell by a comma and feed this into an array. 3) I then write the value for each element into the array into a new cell in a different spreadsheet.

When I add array(0), my formula works because there is always one entry (although it's not always comma separated with additional entries).

When I add array(1), my formula conditionally works because there are some instances where it would have a value from splitting the cell by a comma and accessing the second entry.

However, many times array(1) doesn't have a value and I get an subscript out of range error.

How can I conditionally check when the array element I'm accessing doesn't have a value to avoid this?

I currently have something like:

Workbook.Worksheets("name").Cells(x,y).Value = array(1)

I want to do something like:

If (IsEmpty(array(1))) Then
    Workbook.Worksheets("name").Cells(x,y).Value = ""
Else 
    Workbook.Worksheets("name").Cells(x,y).Value = array(1)

But this also threw a subscript error. Any advice?

To check the number of elements in an array, use UBound , eg

If UBound(array) > 0 Then
    ... access array(1)
Else
    ... write a blank string.
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM