VBA Excel - 矩形网格数据到列中

时间:2012-01-19 03:01:20

标签: vba excel-vba excel

我希望能够将矩形数据网格重新排序为列。我编写了一些代码并运行一些MsgBox来测试一些东西,它似乎工作正常,除了最后一行。也就是说,我已经测试过以确保outputArray实际上最终得到了数据以及其他各种内容。但是,当我尝试将outputArray中的数据写入工作表时,它只是输入所有空格(我有一个以前的版本没有自动删除原始数据,所以我只能看到第一列被清空)。我认为这是一个我无法看到的容易犯的错误。你能帮我弄清楚什么是错的吗? (Excel 2010)

Sub PutDataIntoColumn()
' This sub assumes data comes in a rectangular grid
' And that data is read across row 1, then across row 2, and so on
' The data is reordered into a column of data and is output starting at the top left cell of the original rectangular grid
' The original grid of data is erased so only the column remains

    Dim inputRange As Range
    Dim inputArray() As Variant, outputArray() As Variant

    Set inputRange = Application.InputBox(Prompt:="Select Data", Title:="Data Into Column", Type:=8)
    inputArray = inputRange.Value

    ' Erase the data
    inputRange.Value = ""

    numRows = UBound(inputArray, 1)
    numCols = UBound(inputArray, 2)

    totalCells = numRows * numCols

    ReDim outputArray(totalCells, 1)

    firstCellRow = inputRange.Row
    firstCellCol = inputRange.Column

    For i = 1 To numRows
        For j = 1 To numCols
            outputArray((i - 1) * numCols + j, 1) = inputArray(i, j)
        Next j
    Next i

    ActiveSheet.Cells(firstCellRow, firstCellCol).Resize(totalCells).Value = outputArray

End Sub

1 个答案:

答案 0 :(得分:1)

您正在寻找的简单错误是outputArray缺少明确的下限。将ReDim更改为

ReDim outputArray(1 To totalCells, 1 To 1)

如果没有这个outputArray被声明为0,那么一行和一列比你预期的要大

仅供参考,inputRange.Value = ""的替代inputRange.Clear