You need to enable JavaScript to run this app. VBA CopyPaste宏用Do Loop Until实现sh2 A列空白时终止循环
优惠活动
大模型
产品
解决方案
定价
更多

VBA CopyPaste宏用Do Loop Until实现sh2 A列空白时终止循环

Excel VBA CopyPaste 子过程改造实现方案

完整可运行的改造后代码

Sub CopyPaste()
    ' 关闭屏幕更新提升运行速度
    Application.ScreenUpdating = False
    
    ' 定义工作表对象
    Dim sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet
    Dim currentRow As Long ' 跟踪sh2遍历行、sh3输出行的行号
    
    ' 绑定数据源工作表
    Set sh1 = ThisWorkbook.Worksheets("Sheet1")
    Set sh2 = ThisWorkbook.Worksheets("Sheet2")
    
    ' 处理目标工作表:不存在则新建,已存在则清空原有数据(可根据需求调整清空逻辑)
    On Error Resume Next
    Set sh3 = ThisWorkbook.Worksheets("Brand By Vendor")
    On Error GoTo 0
    If sh3 Is Nothing Then
        Set sh3 = ThisWorkbook.Worksheets.Add(after:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
        sh3.Name = "Brand By Vendor"
    Else
        sh3.Cells.Clear ' 清空原有旧数据,避免重复运行时数据叠加
    End If
    
    ' 设置表头
    sh3.Range("A1") = "门店"
    sh3.Range("B1") = "品牌"
    ' 可根据需求新增其他表头
    
    ' 初始化行号:从第2行开始(跳过表头行)
    currentRow = 2
    
    ' --------------------------
    ' 改造后的 Do Loop Until 循环段(原标注为loop portion的部分)
    ' --------------------------
    Do
        ' 复制sh2当前行A列的门店值到sh3对应行A列
        sh2.Cells(currentRow, "A").Copy Destination:=sh3.Cells(currentRow, "A")
        
        ' 复制sh1指定区域数据到sh3对应行B列,可根据实际数据源调整sh1的列范围
        ' 示例:如果需要复制sh1的B:D列到sh3的B:D列,可修改为sh1.Range("B" & currentRow & ":D" & currentRow).Copy Destination:=sh3.Range("B" & currentRow)
        sh1.Cells(currentRow, "A").Copy Destination:=sh3.Cells(currentRow, "B")
        
        ' 行号+1,处理下一行
        currentRow = currentRow + 1
    ' 终止条件:遍历到sh2当前行A列单元格为空时自动退出循环
    ' 若需跳过零散空行,可修改为判断当前行是否超过sh2已使用区域的最大行号
    Loop Until IsEmpty(sh2.Cells(currentRow, "A").Value)
    
    ' 恢复屏幕更新
    Application.ScreenUpdating = True
    
    ' 完成提示
    MsgBox "数据复制完成,共处理" & currentRow - 2 & "行数据", vbInformation
End Sub

关键调整说明

  • 循环结构完全采用Do ... Loop Until 后置判断结构,符合需求要求,触发终止的条件为sh2遍历位置的A列单元格为空,无需手动指定最大行号
  • 新增了同名工作表存在的判断、运行时清空旧数据、关闭屏幕更新的优化,避免重复运行报错、减少无效操作
  • 复制区域的范围可根据实际业务调整:如果需要复制多列数据,修改sh1后的区域引用即可,Destination参数只要填目标区域的左上角单元格即可自动对齐粘贴
  • 如果sh2的A列存在中间零散空行、需要遍历到整个A列的末尾才停止,可将终止条件修改为:
    Loop Until currentRow > sh2.UsedRange.Row + sh2.UsedRange.Rows.Count - 1
    

内容的提问来源于stack exchange,提问作者temerson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.06 00:06:10