EXCEL拆分列
EXCEL拆分列,并按照自定義列及表頭 并保持原格式。
Sub NewShts()
Dim d As Object, sht As Worksheet, arr, brr, r, kr, i&, j&, k&, x&
Dim Rng As Range, Rg As Range, tRow&, tCol&, aCol&, pd&
Application.ScreenUpdating = False '關(guān)閉屏幕更新
Application.DisplayAlerts = False '關(guān)閉警告信息提示
Set d = CreateObject(“scripting.dictionary”) 'set字典
Set Rg = Application.InputBox(“請框選拆分依據(jù)列!只能選擇單列單元格區(qū)域!”, Title:=“提示”, Type:=8)
'用戶選擇的拆分依據(jù)列
tCol = Rg.Column '取拆分依據(jù)列列標(biāo)
tRow = Val(Application.InputBox(“請輸入總表標(biāo)題行的行數(shù)?”))
'用戶設(shè)置總表的標(biāo)題行數(shù)
If tRow = 0 Then MsgBox “你未輸入標(biāo)題行行數(shù),程序退出。”: Exit Sub
Set Rng = ActiveSheet.UsedRange '總表的數(shù)據(jù)區(qū)域
arr = Rng '數(shù)據(jù)范圍裝入數(shù)組arr
tCol = tCol - Rng.Column + 1 '計算依據(jù)列在數(shù)組中的位置
aCol = UBound(arr, 2) '數(shù)據(jù)源的列數(shù)
For i = tRow + 1 To UBound(arr) '遍歷數(shù)組arr
If Not d.exists(arr(i, tCol)) Then
d(arr(i, tCol)) = i '字典中不存在關(guān)鍵詞則將行號裝入字典
Else
d(arr(i, tCol)) = d(arr(i, tCol)) & “,” & i '如果存在則合并行號,以逗號間隔
End If
Next
For Each sht In Worksheets '遍歷一遍工作表,如果字典中存在則刪除
If d.exists(sht.Name) Then sht.Delete
Next
kr = d.keys '字典的key集
For i = 0 To UBound(kr) '遍歷字典key值
If kr(i) <> “” Then '如果key不為空
r = Split(d(kr(i)), “,”) '取出item里儲存的行號
ReDim brr(1 To UBound? + 1, 1 To aCol) '聲明放置結(jié)果的數(shù)組brr
k = 0
For x = 0 To UBound?
k = k + 1 '累加記錄行數(shù)
For j = 1 To aCol '循環(huán)讀取列
brr(k, j) = arr(r(x), j)
Next
Next
With Worksheets.Add(, Sheets(Sheets.Count))
'新建一個工作表,位置在所有已存在sheet的后面
.Name = kr(i) '表格命名
.[a1].Resize(tRow, aCol) = arr '放標(biāo)題行
.[a1].Offset(tRow, 0).Resize(k, aCol) = brr '放置數(shù)據(jù)區(qū)域
Rng.Copy '復(fù)制粘貼總表的格式
.[a1].PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
.[a1].Select
End With
End If
Next
Sheets(1).Activate '激活第一個表格
Set d = Nothing '釋放字典
Erase arr: Erase brr '釋放數(shù)組
MsgBox “數(shù)據(jù)拆分完成!”
Application.ScreenUpdating = True '恢復(fù)屏幕更新
Application.DisplayAlerts = True '恢復(fù)警示
End Sub
總結(jié)
- 上一篇: 解决更新页面数据回显时时间不匹配问题:T
- 下一篇: 设计模式行为型-状态模式