简体   繁体   English

Excel VBA运行时错误1004

[英]Excel VBA runtime error 1004

I'm trying to write a macro to paste special formulas but keep getting a runtime error 1004 "PasteSpecial method of Range class failed". 我正在尝试编写一个宏来粘贴特殊公式,但一直得到运行时错误1004“Range类的PasteSpecial方法失败”。

This macro comes directly from using the "Record Macro" provided by Excel. 此宏直接来自使用Excel提供的“记录宏”。

Sub paste_formulas()
  Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
         SkipBlanks:=False, Transpose:=False
End Sub

Here is the sequence of events: 以下是事件序列:

  1. Manually select a range of cells in CSV file A and copy (CTRL+C). 在CSV文件A中手动选择一系列单元格并复制(CTRL + C)。
  2. Switch to the XLS file B and select the cell were I want the copied data pasted. 切换到XLS文件B并选择我希望粘贴复制数据的单元格。
  3. Press Macros and run personal.xlsm!paste_formulas 按宏并运行personal.xlsm!paste_formulas

That's when I get the error. 那是我收到错误的时候。 Why does this work manually when I copy/paste-special formulas, but fail in the macro? 为什么我在复制/粘贴特殊公式时手动工作,但在宏中失败?

Note: I need this to work in the above sequence regardless of the selected range that I copy (will vary from time to time), and regardless of the location I paste formulas to (will also vary from time to time). 注意:我需要这个以上述顺序工作,无论我复制的选定范围(会不时变化),无论我粘贴公式的位置如何(也会不时变化)。 In other words, hardcoding a fixed range for copy and/or paste won't work for me. 换句话说,硬编码复制和/或粘贴的固定范围对我来说不起作用。

Thanks in advance for any help understanding why my code isn't working or providing a work-around. 提前感谢任何帮助,了解我的代码无法正常工作或提供解决方法。

The reason is very simple, When you copy from the CSV and then in your workbook, click on Macros in the Developer Toolbar, Excel clears the clipboard. 原因很简单,当您从CSV复制然后在工作簿中复制时,单击开发人员工具栏中的Macros ,Excel将清除剪贴板。

Excel has this habit of clearing the clipboard when you click on Developer | Macros 当您单击Developer | Macros时,Excel有清除剪贴板的习惯 Developer | Macros . Developer | Macros To demonstrate this, copy the cells from the same workbook. 为了演示这一点,请复制同一工作簿中的单元格。 You will see the ant like border around the cells. 你会看到蚂蚁像细胞周围的边界。 Now in the same workbook, click on Developer | 现在在同一个工作簿中,单击Developer | Macros. 宏。 The Ant like borders will disappear :) 像边框一样的Ant会消失:)

在此输入图像描述

Set a shortcut key for your macro and use that. 设置宏的快捷键并使用它。 it will work :) 它会工作:)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM