|
|
- Sub SplitByCommaToNewSheet()
- Dim wsSource As Worksheet, wsDest As Worksheet
- Dim lastRow As Long, i As Long, j As Long, k As Long
- Dim splitValues As Variant
- Dim dataArr() As Variant
- Dim resultArr() As Variant
- Dim itemCount As Long, totalItems As Long
- Dim outputRow As Long
-
- ' 设置源工作表(这里使用活动工作表)
- Set wsSource = ActiveSheet
-
- ' 创建新工作表用于输出结果
- Set wsDest = Worksheets.Add(After:=wsSource)
- wsDest.Name = "拆分结果_" & Format(Now, "yyyymmdd_hhmmss")
-
- ' 获取源数据最后一行
- lastRow = wsSource.Cells(wsSource.Rows.Count, "B").End(xlUp).Row
-
- ' 将源数据读入数组(A到D列)
- dataArr = wsSource.Range("A1:D" & lastRow).Value
-
- ' 先计算总项目数,以确定结果数组大小
- totalItems = 0
- For i = 1 To UBound(dataArr, 1)
- If Not IsEmpty(dataArr(i, 2)) Then
- splitValues = Split(dataArr(i, 2), ",")
- totalItems = totalItems + (UBound(splitValues) + 1)
- Else
- totalItems = totalItems + 1
- End If
- Next i
-
- ' 重新定义结果数组(行数=总项目数,列数=4)
- ReDim resultArr(1 To totalItems, 1 To 4)
-
- ' 填充结果数组
- outputRow = 1
- For i = 1 To UBound(dataArr, 1)
- If Not IsEmpty(dataArr(i, 2)) Then
- splitValues = Split(dataArr(i, 2), ",")
- For j = LBound(splitValues) To UBound(splitValues)
- ' A列(原始值)
- resultArr(outputRow, 1) = dataArr(i, 1)
- ' B列(拆分后的值,去除前后空格)
- resultArr(outputRow, 2) = Trim(splitValues(j))
- ' C列(原始值)
- resultArr(outputRow, 3) = dataArr(i, 3)
- ' D列(原始值)
- resultArr(outputRow, 4) = 1 'dataArr(i, 4) 这个1是我改的
- outputRow = outputRow + 1
- Next j
- Else
- ' 如果B列为空,直接复制整行
- resultArr(outputRow, 1) = dataArr(i, 1)
- resultArr(outputRow, 2) = ""
- resultArr(outputRow, 3) = dataArr(i, 3)
- resultArr(outputRow, 4) = dataArr(i, 1)
- outputRow = outputRow + 1
- End If
- Next i
-
- ' 将结果数组写入新工作表
- With wsDest
- ' 写入标题(如果需要)
- .Range("A1:D1").Value = Array("A列", "B列(拆分后)", "C列", "D列")
- '设置单元格格式为文本
- .Range("a:c").NumberFormatLocal = "@" '这一句是我后加的
- ' 写入数据
- .Range("A2").Resize(UBound(resultArr, 1), UBound(resultArr, 2)).Value = resultArr
- ' 自动调整列宽
- .Columns("A:D").AutoFit
- End With
-
- MsgBox "处理完成!共拆分 " & totalItems & " 行数据。", vbInformation
- End Sub
复制代码 |
|