用VBA写一个一行转多行数据
时间: 2024-03-17 07:39:43 浏览: 125
VBA数据转换
您好,下面是将一行数据转换为多行数据的VBA代码:
```VBA
Sub OneRowToMultiRows()
Dim ws As Worksheet
Dim sourceRange As Range
Dim targetRange As Range
Dim lastColumn As Long
Dim i As Long, j As Long, k As Long
Set ws = ActiveSheet
Set sourceRange = Selection
Set targetRange = sourceRange.Offset(sourceRange.Rows.Count, 0).Resize(1, 1)
lastColumn = sourceRange.Columns.Count
For i = 1 To sourceRange.Rows.Count
For j = 1 To lastColumn
If sourceRange.Cells(i, j) <> "" Then
targetRange.Offset(k, 0).Value = sourceRange.Cells(i, j)
k = k + 1
End If
Next j
Next i
sourceRange.ClearContents
targetRange.Resize(k, 1).Select
End Sub
```
您可以先选择需要转换的一行数据,然后运行以上代码。它将会把一行数据中的非空单元格转换为多行数据,并将转换后的数据显示在原数据下方。转换后的数据将会被选中,原数据也会被清除。希望能对您有所帮助。
阅读全文