|
练手
- Rem 过程开始 X改为你想要的名字
- Public Sub X()
- Rem 代码从这里开始写
- Rem 声明工作簿变量wb和工作表变量sht
- Rem 创建一个字典dic
- Set dic = CreateObject("Scripting.Dictionary")
- Dim wb As Workbook, sht As Worksheet
- Rem 设置wb为当前工作簿
- Set wb = Application.ThisWorkbook
- Rem 设置sht为指定名称的工作表,引号内填写工作表名称
- Set sht = wb.Worksheets("基础数据列表")
- Rem 设置psht为工作表,在引号内填写工作表名称
- Set psht = wb.Worksheets("领料模板")
- Rem 使用With语句,方便对工作表Sht进行多次操作
- With sht
- '.Usedrange.Offset(1).clear
- Rem 获取列A中最大数据行的行号
- eRow = .Cells(.Rows.Count, 1).End(xlUp).Row
- Rem 设置范围从A2开始到Z列的eRow行结束
- Set Rng = .Range("A2:C" & eRow)
- Rem 将范围Rng的值赋给数组Arr
- arr = Rng.Value
- Rem 变量 i 从数组Arr最小索引开始,遍历至其最大索引
- For i = LBound(arr) To UBound(arr)
- Key = CStr(arr(i, 3))
- Rem 若字典dic中不存在键key 则执行
- If Not dic.Exists(Key) Then
- Rem 创建一个字典d
- Set d = CreateObject("Scripting.Dictionary")
- Else
- Rem 若字典dic中存在键key 则执行
- Set d = dic(Key)
- End If
- d(i) = Array(arr(i, 1), arr(i, 2))
- Set dic(Key) = d
- Next i
- End With
- For Each k In dic
- Rem 若后续代码出错,忽略错误继续执行
- On Error Resume Next
- 'vvvvvvvvvvvvvv
- Rem 可能出错的语句放这里
- Rem 关闭警示弹窗
- Application.DisplayAlerts = False
- wb.Worksheets(k).Delete
- Rem 恢复警示弹窗
- Application.DisplayAlerts = True
- '^^^^^^^^^^
- Rem 若前面代码出错,恢复对错误的捕获
- On Error GoTo 0
- psht.Copy after:=wb.Worksheets(wb.Worksheets.Count)
- Rem 设置osht为工作表
- Set osht = wb.Worksheets(wb.Worksheets.Count)
- With osht
- .Name = k
- .Range("a4").Value = k
- Set d = dic(k)
- If d.Count > 5 Then .Range("a14").Resize(d.Count - 5, 1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
- Rem 设置范围为A2单元格
- Set Rng = .Range("A9").Resize(d.Count, 2)
- Rem 如果字典有元素,则将字典的项目转置后输出到指定范围Rng
- Rng.Value = WorksheetFunction.Transpose(WorksheetFunction.Transpose(d.items))
- End With
- Next k
- End Sub
- Rem 过程结束
复制代码 |
|