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

VBA多工作表值粘贴时出现1004错误求助

问题原因

错误出在wsh.Range(Cells(i, 1), Cells(i, 42))这行代码里。Cells(i,1)和Cells(i,42)没有明确指定所属工作表,默认会指向当前活动工作表。当循环到非活动的工作表wsh时,用活动表的单元格去定义另一个工作表的Range范围,会导致对象引用不匹配,触发1004错误。

修复方案

方案1:给Cells指定所属工作表

给所有Cells调用加上wsh.前缀,确保它们和外层的wsh.Range属于同一个工作表:

Private Sub CommandButton1_Click()
    Dim wsh As Worksheet
    Dim i As Integer ' 显式声明变量类型,避免隐性错误
    
    For Each wsh In ThisWorkbook.Worksheets
        For i = 6 To 10
            If Not IsEmpty(wsh.Cells(i, "C")) Then
                wsh.Range(wsh.Cells(i, 1), wsh.Cells(i, 42)).Copy
                wsh.Range(wsh.Cells(i, 1), wsh.Cells(i, 42)).PasteSpecial Paste:=xlPasteValues
            End If
        Next
    Next
    Application.CutCopyMode = False
End Sub

方案2:直接赋值(更高效)

复制粘贴属于耗时操作,直接把单元格的值赋值给自己,效果相同且速度更快:

Private Sub CommandButton1_Click()
    Dim wsh As Worksheet
    Dim i As Integer
    Dim targetRange As Range
    
    For Each wsh In ThisWorkbook.Worksheets
        For i = 6 To 10
            If Not IsEmpty(wsh.Cells(i, "C")) Then
                Set targetRange = wsh.Range(wsh.Cells(i, 1), wsh.Cells(i, 42))
                targetRange.Value = targetRange.Value
            End If
        Next
    Next
End Sub
额外提醒
  • 在模块开头加上Option Explicit,强制显式声明变量,能避免因变量名拼写错误导致的隐性问题。
  • 操作多个工作表时,所有单元格引用都要明确指定父工作表,别依赖默认的活动表引用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 22:31:11