利用Excel中vba代码宏实现
原始数据:
自动生成后数据:
vba实现代码:
Sub CombineColumns()Dim ws As WorksheetDim lastRowA As Long, lastRowB As Long, i As Long, j As LongDim MyIndex As IntegerDim 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).RowlastRowB = ws.Cells(ws.Rows.Count, strColB).End(xlUp).RowMyIndex = 1' 遍历A列For i = 1 To lastRowAstrCombine = "" ' 重置组合字符串' 遍历B列For j = 1 To lastRowBws.Cells(MyIndex, strColC).Value = ws.Cells(i, strColA).Valuews.Cells(MyIndex, strColD).Value = ws.Cells(j, strColB).ValueMyIndex = MyIndex + 1Next jNext i
End Sub
使用方式:
1、首先,工具步骤“开发工具——VB编辑器”,打开WPS/Excel表格里的VB编辑器。
2、执行