利用Excel中vba代码宏实现
原始数据:
自动生成后数据:
vba实现代码:
Sub CombineColumns()
Dim ws As Worksheet
Dim lastRowA As Long, lastRowB As Long, i As Long, j As Long
Dim MyIndex As Integer
Dim strCombine As String, strColA As String, strColB As String, strColC As String, strColD As String
'说明每遍历一A次分子列其包含内容都是全部B原子列
' ****************配置项开始****************
' 设置分子数据源列
strColA = "A" ' 此处对应A列名
' 设置原子数据源列
strColB = "B" ' 此处对B列名
' 设置分子数据生成列
strColC = "C" ' 此处对应C列名
' 设置原子数据生成列
strColD = "D" ' 此处对应D列名
' 设置工作表
Set ws = ThisWorkbook.Sheets("Sheet1") ' 重要更改为你的工作表名称
' ****************配置项结束****************
' ****************程序开始****************
' 具体执行代码 找到A列和B列的最后一行
lastRowA = ws.Cells(ws.Rows.Count, strColA).End(xlUp).Row
lastRowB = ws.Cells(ws.Rows.Count, strColB).End(xlUp).Row
MyIndex = 1
' 遍历A列
For i = 1 To lastRowA
strCombine = "" ' 重置组合字符串
' 遍历B列
For j = 1 To lastRowB
ws.Cells(MyIndex, strColC).Value = ws.Cells(i, strColA).Value
ws.Cells(MyIndex, strColD).Value = ws.Cells(j, strColB).Value
MyIndex = MyIndex + 1
Next j
Next i
End Sub
使用方式:
1、首先,工具步骤“开发工具——VB编辑器”,打开WPS/Excel表格里的VB编辑器。
2、执行