VBA code error when array value exceeds 255 charac

2019-08-02 18:07发布

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?

1条回答
仙女界的扛把子
2楼-- · 2019-08-02 18:59

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.

查看更多
登录 后发表回答