VBA:偶尔会发生“工作表类的粘贴方法失败”

一些上下文:下面的macros打开指定目录中的最新文件。 我试图将新打开的工作表中的所有数据复制到另一个工作表中。 有时候,只有有时候 ,我收到1004错误。

“工作表类的粘贴方法失败”。

有时macros观工作。 我无法指出为什么会发生这种情况。

任何人都可以识别代码的问题? 清除剪贴板的工作有时,但并不总是。 另外,我在一个更大的macros中一直使用几个像这样的macros(链接到不同的文件夹)。 偶尔遇到同样的问题

Sub ImportOldRates() 'Declare the variables Dim MyPath As String Dim MyFile As String Dim LatestFile As String Dim LatestDate As Date Dim LMD As Date 'Specify the path to the folder MyPath = "C:\Folder1\Folder2\" 'Make sure that the path ends in a backslash If Right(MyPath, 1) <> "\" Then MyPath = MyPath & "\" 'Get the first Excel file from the folder MyFile = Dir(MyPath & "*.xls", vbNormal) 'If no files were found, exit the sub If Len(MyFile) = 0 Then MsgBox "No files were found...", vbExclamation Exit Sub End If 'Loop through each Excel file in the folder Do While Len(MyFile) > 0 'Assign the date/time of the current file to a variable LMD = FileDateTime(MyPath & MyFile) 'If the date/time of the current file is greater than the latest 'recorded date, assign its filename and date/time to variables If LMD > LatestDate Then LatestFile = MyFile LatestDate = LMD End If 'Get the next Excel file from the folder MyFile = Dir Loop 'Open the latest file Workbooks.Open MyPath & LatestFile Application.DisplayAlerts = False Application.EnableEvents = False Application.Run "ConnectChartEvents" Cells.Select Range("E2").Activate Selection.copy ActiveWindow.Close ActiveSheet.PasteSpecial Format:="Unicode Text", Link:=False, _ DisplayAsIcon:=False, NoHTMLFormatting:=True Application.CutCopyMode = False Selection.Columns.AutoFit Range("A1").Select Application.DisplayAlerts = True Application.EnableEvents = True End Sub 

这样做会更适合作为评论,但是我想添加我的两分钱,但是还没有能力在这里发表评论。

我在macros中不时遇到类似的错误,用于将图表从Excel复制并粘贴到PowerPoint演示文稿中; 至less对于我来说,当macros尝试粘贴到PPT时,错误偶尔会发生,这导致我相信问题在于在Excel程序和PPT程序之间翻转。

由于我懒得想出一个更有效的方法将图像转换到PPT,为了避免大多数情况下的错误,我在下面添加了一行。

 Application.Wait (Now + TimeValue("0:00:01")) 

我在调用PPT之前立即添加了这个,这大大减less了错误的发生(我现在很less得到它,而且当我再次运行macros时也能正常工作)。 它基本上只是迫使macros停下来,等待1秒钟,然后再继续,让程序在尝试粘贴数据之前赶上。 在理论上有更直接的方法来完成这一点,比如DoEvents ,它应该让macros等待,直到当前的过程完成,但是这从来没有为我解决过这个问题。

感谢大家的贡献。

事实certificate,这个问题是由…造成的

  Range("E2").Activate 

复制整个工作表有时会耗尽我的系统内存,导致复制function失败。 对于那些感兴趣的,我只是select一个较小的范围。

  Range("A1,Z400").Activate 

这解决了这个问题