1

我需要按照下面的方式扩展数组。搜索答案,但似乎没有任何帮助,如下代码所示。

Sub MakeOneColumn()

Dim vaCells As Variant
Dim vOutput() As Variant
Dim i As Long, j As Long
Dim lRow As Long

If TypeName(Selection) = "Range" Then
    If Selection.Count > 1 Then
        If Selection.Count <= Selection.Parent.Rows.Count Then
            vaCells = Selection.Value

            ReDim vOutput(1 To UBound(vaCells, 1) * UBound(vaCells, 2), 1 To 1)

            For j = LBound(vaCells, 2) To UBound(vaCells, 2)
                For i = LBound(vaCells, 1) To UBound(vaCells, 1)
                    If Len(vaCells(i, j)) > 0 Then
                        lRow = lRow + 1
                        vOutput(lRow, 1) = vaCells(i, j)
                    End If
                Next i
                lRow = lRow + 1
            Next j

            Selection.ClearContents
            Selection.Cells(1).Resize(lRow).Value = vOutput
        End If
    End If
End If

End Sub

上面的代码在没有添加行“lRow = lRow + 1”的情况下工作。但是,我需要为数组中的每一列留一个空白行。随着添加的行,我得到一个运行时错误 9,下标超出范围。

4

2 回答 2

1

请将您的 redim 声明更改为以下

  ReDim vOutput(1 To (UBound(vaCells, 1) * UBound(vaCells, 2)) + UBound(vaCells, 2), 1 To 1)
于 2013-03-11T01:40:43.937 回答
0

您收到错误是因为您迭代 lrow 两次,一次在i循环中,一次在j循环中。如果您检查,您应该会发现该错误仅在选择的所有单元格中都有值时发生。

lrow修复方法是设置j 和 i 循环外部的初始值,然后将当前单元格的值分配给vOutput. 它看起来像这样:

  lRow = 1
  For j = LBound(vaCells, 2) To UBound(vaCells, 2)
      For i = LBound(vaCells, 1) To UBound(vaCells, 1)
          If Len(vaCells(i, j)) > 0 Then
              vOutput(lRow, 1) = vaCells(i, j)
              lRow = lRow + 1
          End If
      Next i
  Next j

顺便说一句,我会注意到您不需要TypeName测试,因为选择始终是 Range 类型。

于 2013-03-11T01:25:19.090 回答