Excel VBA 按分组提取每组首行数据至其他工作表的实现咨询
实现思路
- 确认分组判断字段:你当前的分组依据为Sheet1中A列的1-10编号,只需在遍历源数据行时记录已经提取过的分组编号,遇到和上一次提取分组不同的行时,就判定为新分组的首行,写入目标表即可。
- 遍历范围适配数据长度:不要固定循环次数,改为遍历到源表A列最后一个非空行即可,适配不同分组行数不确定的场景。
- 边界处理:源表首个数据行(排除表头行)直接判定为第一个分组的首行,无需对比判断。
原代码问题说明
原代码固定循环10次,每次遍历都直接复制当前行数据,没有做分组重复判断,会将同一个分组的多行数据依次写入目标表,不符合仅取每个分组首行的需求。
修正后可用代码
Sub GenerateReport() Dim RowCountCopy As Long Dim RowCountPaste As Long Dim lastGroup As Integer Dim currentGroup As Integer Dim sourceSheet As Worksheet Dim targetSheet As Worksheet ' 绑定工作表,减少后续重复调用出错概率 Set sourceSheet = ThisWorkbook.Sheets("Sheet1") Set targetSheet = ThisWorkbook.Sheets("Sheet2") ' 初始化行号 RowCountCopy = 2 ' 源表从第2行开始读,默认第1行为表头 RowCountPaste = 3 ' 目标表从第3行开始写 lastGroup = -1 ' 初始值设为不存在的分组编号,用于首行判断 ' 循环遍历源表所有有数据的行 Do While sourceSheet.Range("A" & RowCountCopy) <> "" currentGroup = sourceSheet.Range("A" & RowCountCopy).Value ' 判断是否为新分组的首行 If currentGroup <> lastGroup Then ' 复制对应列数据到目标表 targetSheet.Range("A" & RowCountPaste) = sourceSheet.Range("A" & RowCountCopy) targetSheet.Range("B" & RowCountPaste) = sourceSheet.Range("B" & RowCountCopy) targetSheet.Range("C" & RowCountPaste) = sourceSheet.Range("F" & RowCountCopy) ' 更新目标写入行号、上一个已提取分组编号 RowCountPaste = RowCountPaste + 1 lastGroup = currentGroup End If ' 源表读取行号下移 RowCountCopy = RowCountCopy + 1 Loop End Sub
内容的提问来源于stack exchange,提问作者nikolayDudrenov
相关产品推荐
相关产品推荐

