简体   繁体   English

数组值超过255个字符时VBA代码错误

[英]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. 在此示例中,单元格B3,C3和D3中的值可能是文本,日期,数字。

This code executes fine as long as the text contents of each cell in the range specified does not exceed 255 characters. 只要指定范围内每个单元格的文本内容不超过255个字符,此代码即可正常执行。 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. 我已经阅读了Excel中的各种String限制(使用2010),针对这些限制有各种解决方法。 However given the use of datatype Variant, I am uncertain how one can check for the existence of a text value exceeding these limits. 但是,考虑到使用数据类型Variant,我不确定如何检查是否存在超出这些限制的文本值。

Is anyone able to suggest how one might adjust the code to allow for greater text length than 255 characters? 有谁能建议如何调整代码以允许超过255个字符的文本长度?

Adjusted my code as per Tim's suggestion to access the array directly rather than using the Worksheet.Index. 根据Tim的建议调整了我的代码,以直接访问数组而不是使用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. 这避免了255个字符限制的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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