简体   繁体   中英

VBA code error when array value exceeds 255 characters

I have extracted the following code snippet from a project I am working on :

Sub testData()

Dim dataRange As Range
Set dataRange = Range("B2").Offset(1, 0).Resize(, 3)

Dim data As Variant
data = dataRange.Value2

Dim i As Integer
For i = 1 To UBound(data)
    Dim datarow As Variant
    datarow = WorksheetFunction.Index(data, i, 0)

    For j = 1 To dataRange.Count
        MsgBox "The data is " & datarow(j)
    Next j
Next i

End Sub

Values in Cells B3, C3 and D3 in this example might be text, date, number.

This code executes fine as long as the text contents of each cell in the range specified does not exceed 255 characters. If greater, the code will throw an error at the line :

datarow = WorksheetFunction.Index(data, i, 0)

I have read about various String limits in Excel (using 2010) for which there are various workarounds. However given the use of datatype Variant, I am uncertain how one can check for the existence of a text value exceeding these limits.

Is anyone able to suggest how one might adjust the code to allow for greater text length than 255 characters?

Adjusted my code as per Tim's suggestion to access the array directly rather than using the Worksheet.Index. Updated code as follows :

For i = 1 To UBound(data)
   For j = 1 To dataRange.Count
      MsgBox "The data is " & data(i, j)
   Next j
Next i

This avoids the issue of the 255 character limitation.

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