我使用ctrl + c命令手动复制一个工作表中的一些单元格,并希望使用我创建的宏粘贴它。
我有以下代码:
Range("A2:W5000").Select
Selection.ClearContents
Range("A2").Select
ActiveSheet.Paste
With Selection.Interior
.PatternColorIndex = 7
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
Range("A2").Select
这个宏在我的机器上运行得很好,但出于某种原因,当在另一台PC上运行完全相同的宏时,我得到了ActiveSheet.Paste
的错误。
关于为什么会发生这种情况的任何想法?
提前感谢您提出任何建议。
答案 0 :(得分:0)
很可能您正在使用受保护的工作表。因此,您收到1004
错误。在做任何事情之前,尝试检查teh工作表是否受到保护:
Sub TestMe()
If ActiveSheet.ProtectContents Then
MsgBox ActiveSheet.Name & " is protected!"
Else
Range("A2:W5000").Select
Selection.ClearContents
Range("A2").Select
ActiveSheet.Paste
With Selection.Interior
.PatternColorIndex = 7
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
Range("A2").Select
End If
End Sub
答案 1 :(得分:0)
我认为PEH有正确的答案。但我更新了您的代码以反映
Dim ws as Worksheet
set ws = ActiveSheet 'Setting the worksheet object and then referencing it for each Range will ensure that the macro doesn't get confused as to which sheet it should be getting the Range from.
ws.Range("A2:W5000").ClearContents 'No need to select cells first before clearing them
ws.Range("A2").PasteSpecial 'Once again, no need to select before pasting. It will do a normal paste if you do PasteSpecial only, but if you wanted to say paste values only it would look like this .PasteSpecial(xlPasteValues)
With ws.Range("A2").Interior
.PatternColorIndex = 7
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
ws.Range("A2").Select 'No necessary unless you think that A2 won't be visible when the other user uses this macro. No harm in leaving it in though.
希望这对你有帮助。祝好运! 杰森
答案 2 :(得分:0)
问题是您在之前开始复制运行该宏。但是,如果您在宏中使用.ClearContents
,则副本选择会丢失。
因此.PasteSpecial
之后的.ClearContents
无效。
您可以使用
轻松测试Sub test()
Range("A1").Copy
Debug.Print Application.CutCopyMode '=1 means something is copied
Range("A2").ClearContents 'kills cutcopymode
Debug.Print Application.CutCopyMode '=0 means nothing is copied
Range("A3").PasteSpecial 'fails because nothing is selected for copy anymore
End Sub
所以解决方案就是......
.ClearContents
或在.Paste
之前杀死副本选择的任何其他操作。.ClearContents
然后