一些上下文:以下宏打开指定目录中的最新文件。我试图将新打开的工作表中的所有数据复制到另一个工作表中。有时,只有有时,我会收到 1004 错误。
“工作表类的粘贴方法失败”。
有时宏有效。我无法确定为什么会发生这种情况。
任何人都可以识别代码的问题吗?清除剪贴板有时有效,但并非总是如此。此外,我一直在一个更大的宏中使用几个宏(链接到不同的文件夹)。我偶尔会遇到同样的问题。
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
Run Code Online (Sandbox Code Playgroud)
小智 7
这将更适合作为评论,但我想添加我的两分钱,但还没有能力在这里发表评论。
我在用于将 Excel 中的图表复制并粘贴到 PowerPoint 演示文稿中的宏中不时遇到类似的错误;至少对我来说,当宏试图粘贴到PPT中时,偶尔会发生错误,这让我相信问题在于Excel程序和PPT程序之间的翻转。
由于我懒得想出更有效的方法将图像导入PPT,所以我在下面添加了一行,以避免在大多数情况下出现错误。
Application.Wait (Now + TimeValue("0:00:01"))
Run Code Online (Sandbox Code Playgroud)
我在调用翻转到 PPT 之前立即添加了这个,它大大减少了错误的发生(我现在很少得到它,当我再次运行宏时可以正常工作)。它基本上只是强制宏在继续之前停止并等待 1 秒,允许程序在尝试粘贴数据之前赶上。理论上有更直接的方法可以实现这一点,例如DoEvents应该让宏等待当前进程完成,但这从来没有为我解决这个问题。
感谢大家的贡献。
事实证明,这个问题是由
Range("E2").Activate
Run Code Online (Sandbox Code Playgroud)
复制整张纸有时会耗尽我的系统内存并导致复制功能失败。对于那些感兴趣的人,我只是选择了一个较小的范围。
Range("A1,Z400").Activate
Run Code Online (Sandbox Code Playgroud)
这解决了问题