将变量数组转储到范围 - VBA excel错误1004

Pre*_*sen 5 excel vba excel-2003 excel-vba

我正在使用 for Excel,以便通过以下方式将数据保存到数组中:

Dim allPosts As Variant
allPosts = Range("A2:J5000")
Run Code Online (Sandbox Code Playgroud)

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

Range("A2:J5000").Value = allPosts
Run Code Online (Sandbox Code Playgroud)

我收到错误:

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

并且复制在特定单元格停止,当我将此单元格中的字符串更改为更短时,问题就解决了.

谢谢

bre*_*tdj 12

您可以使用第二个数组来存储太长的单元格长度,并单独迭代它们

这个Microsoft支持文章 无法处理写回超过911个字符的数组字符串在我的测试中正常工作)

代码如下:

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

    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
Run Code Online (Sandbox Code Playgroud)

  • 太好了!非常好. (3认同)