I want to be able to reorder a rectangular grid of data into a column. I have written some code and run some MsgBox’s to test some things and it seems to work right, except for the last line. That is, I have tested to make sure outputArray actually ends up with data in it and various other things. But, when I try to write the data in outputArray to the worksheet, it just enters all blanks (I had a previous version which didn’t automatically delete the original data, so I could see just the first column being blanked out). I assume it’s some easy mistake I can’t see. Can you help me figure out what’s wrong? (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
The easy mistake you are looking for is the lack of explicit lower bounds on your
outputArray. Change theReDimtoWithout this
outputArrayis declared 0 based, so is one row and column bigger than you expectedFYI, an alternative to
inputRange.Value = ""isinputRange.Clear