我尝试坚持使用数组(通常我喜欢反过来);只有数值被转置,用户进行选择。工作表上应预定义一个名为"Vba_output"
的命名范围。
Sub Transpose_and_flush_table()
Dim source_array As Variant
Dim target_array As Variant
Dim source_column_counter As Long
Dim source_row_counter As Long
Dim blanks As Long
Const row_index = 1
Const col_index = 2
source_array = Selection.Value
' source_array(row,column)
ReDim target_array(UBound(source_array, col_index), UBound(source_array, row_index))
For source_column_counter = _
LBound(source_array, col_index) To UBound(source_array, col_index)
blanks = 0
'Count blank cells
For source_row_counter = _
LBound(source_array, row_index) To UBound(source_array, row_index)
If source_array(source_row_counter, source_column_counter) = "" Then
blanks = blanks + 1
End If
Next
'Replace blanks, shift array elements to the left
For source_row_counter = _
LBound(source_array, row_index) To UBound(source_array, row_index) - blanks
source_array(source_row_counter, source_column_counter) = _
source_array(source_row_counter + blanks, source_column_counter)
Next
'Add blanks to the end
For source_row_counter = _
UBound(source_array, row_index) - blanks + 1 To UBound(source_array, row_index)
source_array(source_row_counter, source_column_counter) = ""
Next
'Transpose source and target arrays
For source_row_counter = _
LBound(source_array, row_index) To UBound(source_array, row_index)
target_array(source_column_counter, source_row_counter) = _
source_array(source_row_counter, source_column_counter)
Next
Next
Range("Vba_output").Offset(-1, -1).Resize(UBound(target_array, row_index) + 1, _
UBound(target_array, col_index) + 1) = target_array
End Sub