将variables数组转换为范围 – VBA excel错误1004

我使用Excel的VBA为了保存数据到一个数组:

Dim allPosts As Variant allPosts = Range("A2:J5000") 

之后,我正在更改allPosts数组中的数据,然后我想通过以下方法将其粘贴回来:

 Range("A2:J5000").Value = allPosts 

我收到错误:

运行时错误1004应用程序定义的或对象定义的

和复制停止在一个特定的单元格,当我改变在这个单元格的string是更短的问题得到解决。

谢谢

您可以使用第二个数组来存储太长的单元格长度,并分别对这些数据进行迭代

从这微软支持文章 excel-2003不能处理回写比911字符更长的数组字符excel-2010在我的testing中工作得很好)

下面的代码:

  1. 设置读取范围内的主要变体数组
  2. 设置与第一个数组大小相等的第二个空白变体
  3. testing数组的每个部分的长度超过911个字符的单元格长度然后
    • 操纵第一个数组中较短的值,或者,
    • 从第一个数组中删除该值,然后将其写入第二个数组
  4. 第一个arrays被扔回一个单一的范围内
  5. 第二个数组是逐个单元格迭代以转储其他string

  Sub KudosRickyPonting() Dim allPosts As Variant Dim allPosts2 As Variant Dim vStrs As Variant Dim lngRow As Long Dim lngCol As Long allPosts = Range("A2:J5000").Value2 ReDim allPosts2(1 To UBound(allPosts, 1), 1 To UBound(allPosts, 2)) For lngRow = 1 To UBound(allPosts, 1) For lngCol = 1 To UBound(allPosts, 2) If Len(allPosts(lngRow, lngCol)) < 912 Then allPosts(lngRow, lngCol) = "Updated:" & allPosts(lngRow, lngCol) Else allPosts2(lngRow, lngCol) = "NEW PART " & allPosts(lngRow, lngCol) 'erase long value from first array allPosts(lngRow, lngCol) = vbNullString End If Next Next Range("A2:J5000").Value = allPosts For lngRow = 1 To UBound(allPosts2, 1) For lngCol = 1 To UBound(allPosts2, 2) If Len(allPosts2(lngRow, lngCol)) > 0 Then Range("A2").Offset(lngRow - 1, lngCol - 1).Value2 = allPosts2(lngRow, lngCol) Next Next End Sub