I am trying to copy one cell (D1) of sheet1 to a cell (D1) of all the workbook's other sheets (I am looping through files here and the number of worksheet varies).
When running the code below, the line "ActiveSheet.Paste" gives me the following error: "Run-time error '10004': Paste method of Worksheet class failed".
Here is the problematic piece of code:
'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
In case it might be necessary, here is how I defined my loop through files:
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
Suggestions would be most welcome!
Thank you.
I'm guessing which sheet you're copying from...
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
This works for me with a slight alteration:
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
example call:
call MSAallSheets(activeWorkbook, "Page 1", "D1")
The parameters make it easier to change minor details / reuse the code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.