VBA从一张纸复制/粘贴到所有其他纸张

时间:2013-08-05 22:28:15

标签: excel vba excel-vba

我正在尝试将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

建议非常欢迎!

谢谢。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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")

这些参数可以更轻松地更改次要细节/重用代码。