【发布时间】:2016-06-16 16:04:05
【问题描述】:
使用 VBA 将 1 行文本从 word 复制粘贴到 excel。
当代码到达以下行时,我收到以下错误。
ActiveSheet.Paste
运行时错误“1004”:工作表类的粘贴方法失败错误
但是如果我点击调试按钮并按F8,那么它会将数据粘贴到excel中没有任何错误。
每次循环继续并按调试和 F8 很好地粘贴数据时都会发生此错误。
我进行了多次测试,但无法找到此问题的根本原因。
在粘贴数据代码之前也使用了 DoEvents,但没有任何效果。
有什么建议吗?
编辑:-
我发布代码是因为你们俩都说同样的话。这是供您查看的代码。
Sub FindAndReplace()
Dim vFR As Variant, r As Range, i As Long, rSource As Range
Dim sCurrRep() As String, sGlobalRep As Variant, y As Long, x As Long
Dim NumCharsBefore As Long, NumCharsAfter As Long
Dim StrFind As String, StrReplace As String, CountNoOfReplaces As Variant
'------------------------------------------------
Dim oWord As Object
Const wdReplaceAll = 2
Set oWord = CreateObject("Word.Application")
'------------------------------------------------
Application.ScreenUpdating = False
vFR = ThisWorkbook.Sheets("Sheet1").Range("A1").CurrentRegion.Value
On Error Resume Next
Set rSource = Cells.SpecialCells(xlCellTypeConstants)
On Error GoTo 0
If Not rSource Is Nothing Then
For Each r In rSource.Cells
For i = 2 To UBound(vFR)
If Trim(vFR(i, 1)) <> "" Then
With oWord
.Documents.Add
DoEvents
r.Copy
.ActiveDocument.Content.Paste
NumCharsBefore = .ActiveDocument.Characters.Count
With .ActiveDocument.Content.Find
.ClearFormatting
.Font.Bold = False
.Replacement.ClearFormatting
.Execute FindText:=vFR(i, 1), ReplaceWith:=vFR(i, 2), Format:=True, Replace:=wdReplaceAll
End With
.Selection.Paragraphs(1).Range.Select
.Selection.Copy
r.Select
ActiveSheet.Paste'Error occurs in this line pressing debug and F8 is pasting the data
StrFind = vFR(i, 1): StrReplace = vFR(i, 2)
NumCharsAfter = .ActiveDocument.Characters.Count
CountNoOfReplaces = (NumCharsBefore - NumCharsAfter) / (Len(StrFind) - Len(StrReplace))
.ActiveDocument.UndoClear
.ActiveDocument.Close SaveChanges:=False
If CountNoOfReplaces Then
x = x + 1
ReDim Preserve sCurrRep(1 To 3, 1 To x)
sCurrRep(1, x) = vFR(i, 1)
sCurrRep(2, x) = vFR(i, 2)
sCurrRep(3, x) = CountNoOfReplaces
End If
CountNoOfReplaces = 0
End With
End If
Next i
Next r
End If
oWord.Quit
'Some more gode goes here... which is not needed since error occurs in the above loop
End Sub
如果您想知道我为什么选择替换词,请通过以下链接。 http://www.excelforum.com/excel-programming-vba-macros/1128898-vba-characters-function-fails-when-the-cell-content-exceeds-261-characters.html
还使用以下链接中的代码来获取替换次数。
【问题讨论】:
-
你能再展示一些你的代码吗...?
-
感谢您的回复,但代码与此错误完全无关。我的问题是为什么当我按调试并按 F8 时它会起作用,为什么它不自己粘贴数据。
-
the code is not at all related to this error运行时错误是您的代码有问题。除非我们能看到在该错误之前发生了什么,否则我们无能为力。 -
你错了,导致错误的不是
ActiveSheet.Paste,而是之前的所有内容加上.Paste method。显示更多代码可以让我们提出更多问题并提供支持。我们不知道您复制的是哪一行文档,您是如何定义的等等,所以......? -
我已经用您的评论代码更新了我的初始帖子。请建议我无法解决此问题。