You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求优化VBA代码:实现多工作表C列数据及格式批量复制至Summary表

解决VBA复制单元格值及格式的问题

原代码通过数组存储单元格值再写入目标表,仅能传递数据,无法保留字体、颜色、数字格式等格式信息。以下是两种可行的解决方案:

方案一:批量复制粘贴区域(高效推荐)

直接批量复制源工作表的目标区域,粘贴到汇总表时同时保留值和格式,避免逐单元格循环的低效问题:

Sub AuthorityCitation()
    Application.ScreenUpdating = False
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim summaryLastRow As Long
    
    ' 遍历所有非汇总工作表
    For Each ws In ThisWorkbook.Worksheets
        If ws.Name <> "Summary" Then
            ' 获取当前工作表C列最后一行数据行(从第2行开始)
            lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
            If lastRow >= 2 Then ' 确认存在有效数据
                ' 复制C2到C列最后一行的区域
                ws.Range("C2:C" & lastRow).Copy
                ' 定位汇总表C列的下一个空行
                summaryLastRow = ThisWorkbook.Sheets("Summary").Cells(ThisWorkbook.Sheets("Summary").Rows.Count, "C").End(xlUp).Row
                ' 处理汇总表为空的情况
                If summaryLastRow = 1 And ThisWorkbook.Sheets("Summary").Cells(1, "C").Value = "" Then
                    summaryLastRow = 0
                End If
                ' 粘贴所有内容(含值、格式、数字格式等)
                ThisWorkbook.Sheets("Summary").Cells(summaryLastRow + 1, "C").PasteSpecial Paste:=xlPasteAll
            End If
        End If
    Next ws
    
    Application.CutCopyMode = False ' 清除剪贴板状态
    Application.ScreenUpdating = True
End Sub

关键说明:

  • 使用xlPasteAll参数会粘贴单元格的所有属性,包括值、格式、字体、边框等;如果只需保留值和格式,也可替换为xlPasteValuesAndNumberFormats+xlPasteFormats分两次粘贴
  • 批量复制区域比逐单元格循环执行效率更高,适合数据量较大的场景

方案二:逐单元格复制(适合需额外判断的场景)

如果需要对每个单元格做额外逻辑判断,可保留逐行循环,通过Copy+PasteSpecial传递格式:

Sub AuthorityCitation()
    Application.ScreenUpdating = False
    Dim cnt As Integer, i As Integer, ws As Worksheet
    cnt = 0
    
    ' 遍历所有非汇总工作表
    For Each ws In Worksheets
        If ws.Name <> "Summary" Then
            For i = 2 To ws.Cells(Rows.Count, "C").End(xlUp).Row
                cnt = cnt + 1
                ' 复制当前单元格的所有内容(含格式)
                ws.Cells(i, "C").Copy
                ' 粘贴到汇总表对应位置
                ThisWorkbook.Sheets("Summary").Cells(cnt, "C").PasteSpecial Paste:=xlPasteAll
            Next i
        End If
    Next ws
    
    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

关键说明:

  • 逐单元格复制会增加执行时间,数据量较大时不推荐使用
  • 可根据需求调整PasteSpecial的参数,仅粘贴需要的内容(比如xlPasteFormats仅粘贴格式)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 09:15:35