0

我正在尝试将 sheet1 的一个单元格 (D1) 复制到工作簿的所有其他工作表的一个单元格 (D1) 中(我在此处循环文件并且工作表的数量有所不同)。

运行下面的代码时,“ActiveSheet.Paste”行给我以下错误:“运行时错误'10004':Worksheet 类的粘贴方法失败”。

这是有问题的代码段:

'copy MSA code to sheets!=1
Sub MSAallSheets(wb As Workbook)
    With wb
    Range("D1").Copy
        For Each ws In wb.Worksheets
            If ws.Name <> "Page 1" Then
            ws.Activate
            ws.Range("D1").Select
            ActiveSheet.Paste
            End If
        Next
    End With
End Sub

如果有必要,这是我通过文件定义循环的方式:

Dim Filename, Pathname As String
Dim wb As Workbook
Pathname = "C:\Users\julia.anderson\Documents\HMDA\test\"
Filename = Dir(Pathname & "*.xlsx")
Do While Filename <> ""
Set wb = Workbooks.Open(Pathname & Filename)
DoWork wb
Delete wb
MSAallSheets wb
wb.Close SaveChanges:=True
Filename = Dir()
Loop
End Sub

建议将是最受欢迎的!

谢谢你。

4

2 回答 2

0

我猜你是从哪张纸上抄来的……

Sub MSAallSheets(wb As Workbook)
    With wb
    Range("D1").Copy
        For Each ws In wb.Worksheets
            If ws.Name <> "Page 1" Then
                wb.Sheets("Page 1").Range("D1").Copy _
                                      ws.Range("D1")                      
            End If
        Next
    End With
End Sub
于 2013-08-05T22:41:15.723 回答
0

这对我有用,只需稍作改动:

Sub MSAallSheets(wb As Workbook, SourceSheet As String, SourceAddress As String)
    With wb
    Sheets(SourceSheet).Range(SourceAddress).Copy
        For Each ws In wb.Worksheets
            If ws.Name <> SourceSheet Then
                ws.Activate
                ws.Range(SourceAddress).Select
                ActiveSheet.Paste
            End If
        Next
    End With
End Sub

示例调用:

call MSAallSheets(activeWorkbook, "Page 1", "D1")

这些参数使更改次要细节/重用代码变得更加容易。

于 2013-08-05T22:50:41.970 回答