在Excel中输出一个数组

时间:2013-12-18 16:57:58

标签: arrays excel vba excel-vba

我拼凑了以下代码,以便我可以修剪工作表中每个单元格的前导和尾随空格。为了保持表属性,我需要确保我不会弄乱标题行。当我运行时,除了标题行之外,所有内容都被删除。我做错了什么?

这是我第一次处理数组。当我在没有数组的情况下尝试此操作时,代码将需要一段时间来读取和重写工作表中的每个单元格。数组快了很多,我只是不明白如何使用它。

Dim arrData(), arrReturnData() As Variant
Dim rng As Excel.Range
Dim i, j, lRows, lCols As Long

Set rng = ActiveSheet.UsedRange
Set rng = rng.Offset(1, 0).Resize(rng.Rows.Count - 1) 'don't mess with the header row
arrData = rng.Value

lRows = rng.Rows.Count
lCols = rng.Columns.Count

ReDim arrData(1 To lRows, 1 To lCols)
ReDim arrReturnData(1 To lRows, 1 To lCols)

For j = 1 To lCols
    For i = 1 To lRows
    arrReturnData(i, j) = Trim(arrData(i, j))
    Next i
Next j

rng.Value = arrReturnData
Set rng = Nothing

2 个答案:

答案 0 :(得分:4)

您正在分配

arrData = rng.Value

然后重新调整它。因此所有的价值都消失了。

顺便说一下,你根本不需要ReDim arrData(1 To lRows, 1 To lCols)。将excel范围存储到variant数组时,将自动调整数组大小。

尝试和测试

Option Explicit

Sub Sample()
    Dim arrData(), arrReturnData() As Variant
    Dim rng As Excel.Range
    Dim i, j, lRows, lCols As Long

    Set rng = ActiveSheet.UsedRange
    Set rng = rng.Offset(1, 0).Resize(rng.Rows.Count - 1) 

    lRows = rng.Rows.Count
    lCols = rng.Columns.Count

    ReDim arrReturnData(1 To lRows, 1 To lCols)

    arrData = rng.Value

    For j = 1 To lCols
        For i = 1 To lRows
            arrReturnData(i, j) = Trim(arrData(i, j))
        Next i
    Next j

    rng.Value = arrReturnData
    Set rng = Nothing
End Sub

答案 1 :(得分:0)

使用保留

Redim Preserve arrData(1 To lRows, 1 To lCols)