在excelvba中 将数组按照首列所含项目(以;分割)拆分为多行
时间: 2024-02-25 19:57:59 浏览: 152
将EXCEL多行表头的工作表拆分为多个工作表-工具
在Excel VBA中,可以使用类似Python的方式将数组按照首列所含项目拆分为多行,并按照要求进行排序。以下是示例代码:
```vb
Sub SplitAndSortData()
' 原始数据
Dim data As Variant
data = Array("banana;apple;pear" & vbTab & "10" & vbTab & "20" & vbTab & "30", _
"banana" & vbTab & "20" & vbTab & "30" & vbTab & "40", _
"orange;banana" & vbTab & "15" & vbTab & "25" & vbTab & "35", _
"apple" & vbTab & "25" & vbTab & "35" & vbTab & "45")
' 拆分为多行
Dim new_data As Variant
ReDim new_data(1 To 1, 1 To UBound(data) * 3)
Dim i As Long, j As Long, k As Long
For i = 0 To UBound(data)
Dim items As Variant
items = Split(data(i), vbTab)
Dim first_col_items As Variant
first_col_items = Split(items(0), ";")
For j = 0 To UBound(first_col_items)
k = k + 1
new_data(k, 1) = first_col_items(j)
new_data(k, 2) = items(1)
new_data(k, 3) = items(2)
new_data(k, 4) = items(3)
Next j
Next i
ReDim Preserve new_data(1 To k, 1 To 4)
' 按照要求排序
Dim tmp As Variant
For i = 1 To UBound(new_data)
For j = i + 1 To UBound(new_data)
If Len(new_data(i, 1)) > Len(new_data(j, 1)) Or _
(Len(new_data(i, 1)) = Len(new_data(j, 1)) And new_data(i, 1) > new_data(j, 1)) Then
For k = 1 To 4
tmp = new_data(i, k)
new_data(i, k) = new_data(j, k)
new_data(j, k) = tmp
Next k
End If
Next j
Next i
' 输出结果
Dim rng As Range
Set rng = Range("A1").Resize(UBound(new_data), 4)
rng.Value = new_data
End Sub
```
以上代码中,我使用`Array`函数定义了一个原始数据数组,然后使用`Split`函数拆分每个元素,再将首列拆分为多行。最后,我使用冒泡排序对新数组进行排序,并将结果输出到单元格中。请注意,这里使用了一维数组模拟二维数组,需要手动处理数组的维度。
阅读全文