1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| Sub 二维表转一维表() Dim application As Object Dim sh As Object Dim rng As Range Dim arr() As Variant Dim crr() As Variant Dim brr() As Variant Dim rng2 As Range Dim i As Long, j As Long, j2 As Long, k As Long Dim rnum As Long, col As Long Set application = GetObject(, "Excel.Application") Set sh = application.ActiveSheet Set rng = application.Selection arr = rng.Value If rng.Columns.Count = 2 Then If IsNumeric(arr(1, 2)) Then Dim d As Object Set d = CreateObject("Scripting.Dictionary") For i = 1 To UBound(arr) If d.Exists(arr(i, 1)) Then d(arr(i, 1)) = d(arr(i, 1)) + arr(i, 2) Else d(arr(i, 1)) = arr(i, 2) End If Next Set rng = application.InputBox("请选择结果存放区域", "提示", Type:=8) rng.Resize(d.Count, 1).Value = application.Transpose(d.Keys) rng.Offset(0, 1).Resize(d.Count, 1).Value = application.Transpose(d.Items) Else Dim t As String t = arr(1, 2) ReDim brr(UBound(arr) - 2, 2) For i = 2 To UBound(arr) brr(i - 2, 0) = arr(i, 1) brr(i - 2, 1) = t brr(i - 2, 2) = arr(i, 2) Next Set rng = application.InputBox("请选择结果存放区域", "提示", Type:=8) rng.Resize(UBound(arr) - 1, 3).Value = brr End If GoTo EndSub End If If IsNumeric(arr(2, 2)) Then Set rng2 = rng.Offset(0, 1).Resize(1, UBound(arr, 2) - 1) Else Set rng2 = application.InputBox("请选择数据对应的标题字段", "提示", Type:=8) End If If rng2.Row <> rng.Row Then MsgBox "标题行错误" GoTo EndSub End If brr = rng2.Value rnum = rng2.Rows.Count If rnum > 2 Then MsgBox "最多只能选择2行", , "提示" GoTo EndSub End If col = rng2.Column - rng.Column + 1 If rnum > 1 Then For i = 2 To UBound(brr, 2) If brr(1, i) = "" Then brr(1, i) = brr(1, i - 1) Next End If ReDim Preserve crr((UBound(arr) - rnum) * UBound(brr, 2) - 1, col) k = -1 For i = rnum + 1 To UBound(arr) For j = 1 To UBound(brr, 2) k = k + 1 For j2 = 1 To col - 1 crr(k, j2 - 1) = arr(i, j2) Next crr(k, col - 1) = brr(1, j) crr(k, col) = arr(i, col + j - 1) Next Next Set rng = application.InputBox("请选择结果存放区域", "提示", Type:=8) rng.Resize(UBound(crr) + 1, UBound(crr, 2) + 1).Value = crr EndSub: Set application = Nothing Set sh = Nothing Set rng = Nothing End Sub
|