Copy pasting 1 line of text from word to excel using VBA.
When the code reaches the below line I am getting the below error.
ActiveSheet.Paste
Run Time Error ‘1004’: Paste Method Of worksheet Class Failed error
But if I click Debug button and press F8 then it’s pasting the data in excel without any error.
This error occurs each time the loop goes on and pressing debug and F8 pasting the data nicely.
I did several testing and unable to find the root cause of this issue.
Also used DoEvents before pasting the data code but nothing worked.
Any suggestions?
EDIT:-
I am posting the code since both of you are saying the same. Here is the code for your review.
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
If you want to know why I have chosen word for replacement then please go through the below link.
http://www.excelforum.com/excel-programming-vba-macros/1128898-vba-characters-function-fails-when-the-cell-content-exceeds-261-characters.html
Also used the code from the below link to get the number of replacements count.
http://word.mvps.org/faqs/macrosvba/GetNoOfReplacements.htm
extrafant Пользователь Сообщений: 266 |
Собственно, пока код не модернизировал все работало. Теперь сделал корректный выбор только 1 файла, но не вставляются данные. Вроде все делаю самым простым способом. Просто копирую из одного листа и вставляю в другой. Почему же возникает такая ошибка? Запустить: И будет эта самая ошибка |
Sanja Пользователь Сообщений: 14849 |
#2 11.07.2019 12:22:36
Ошибка не воспроизвелась. Согласие есть продукт при полном непротивлении сторон. |
||
extrafant Пользователь Сообщений: 266 |
Private Sub pastedata() Во время ActiveSheet.Paste Это самое paste не происходит |
RAN Пользователь Сообщений: 7139 |
#4 11.07.2019 12:43:39 Замените ВЕСЬ ваш код. Ему припарками не помочь.
|
||
extrafant Пользователь Сообщений: 266 |
Ошибка сохранилась. Хотя я заменил содержимое макроса Private Sub openfile() |
extrafant Пользователь Сообщений: 266 |
#6 11.07.2019 12:47:00
Странно, конечно, что у Вас ошибка не воспроизводится |
||
RAN Пользователь Сообщений: 7139 |
#7 11.07.2019 12:55:48 По ошибке. Строка
сбрасывает буфер, и вставлять нечего. |
||
extrafant Пользователь Сообщений: 266 |
#8 11.07.2019 12:56:53
Закомментил. Ошибка сохранилась. Изменено: extrafant — 11.07.2019 12:58:16 |
||
RAN Пользователь Сообщений: 7139 |
#9 11.07.2019 13:00:32
Если это реакция на мой ответ, то весь код, и текст одной процедуры — вещи разные. |
||
extrafant Пользователь Сообщений: 266 |
#10 11.07.2019 13:06:16
Я разобрался. Ошибки нет. Когда я скопировал Ваш код, то я забыл добавить вот этот участок кода:
Соответственно ничего не копировалось и вставиться уже ничего не могло. СПАСИБО! |
||||
RAN Пользователь Сообщений: 7139 |
#11 11.07.2019 13:21:48
Что значит «забыл»? И зачем в мой код вообще что-либо добавлять? Тем паче эдакое? |
||
extrafant Пользователь Сообщений: 266 |
#12 11.07.2019 13:24:45
Данный участок работал.
сразу ошибка, которая не вставляла данные ушла. И все заработало Понятно, что вставить оно не могло т.к. не было ActiveCell.CurrentRegion.Copy |
||||
crou 0 / 0 / 0 Регистрация: 20.11.2012 Сообщений: 5 |
||||
1 |
||||
20.11.2012, 17:58. Показов 17084. Ответов 8 Метки нет (Все метки)
Добрый день. сгенерировал код при помощи записи макроса:
он должен с первого активного листа копировать диапазон, вставлять его на второй лист в указанное место и делать промежуточные суммы. При пошаговом выполнении под отладкой, все работает как положено, при попытке прикрутить выполнение этого макроса на кнопку или горячую клавишу или просто запуск макроса, на строке ActiveSheet.Paste выдает ошибку что метод Paste завершен неверно. Помогите.
0 |
Скрипт 5471 / 1149 / 50 Регистрация: 15.09.2012 Сообщений: 3,515 |
||||
20.11.2012, 18:05 |
2 |
|||
Это отключает копирование:
1 |
0 / 0 / 0 Регистрация: 20.11.2012 Сообщений: 5 |
|
20.11.2012, 18:21 [ТС] |
3 |
закоментировал, данные скопировались (включая имя диапазона данных и шапку из БД с названиями колонок), но теперь неработает Selection.Subtotal, т.е. не строится промежуточный итог в таблице, так же на панели инструментов неактивна данная функция. Подозреваю что это связано с тем что данные подтягиваются из БД.
0 |
5471 / 1149 / 50 Регистрация: 15.09.2012 Сообщений: 3,515 |
|
20.11.2012, 18:23 |
4 |
crou, новую тему тогда создавайте, т.к. у вас теперь другая задача, которая никак не связана с данной темой.
2 |
0 / 0 / 0 Регистрация: 20.11.2012 Сообщений: 5 |
|
20.11.2012, 21:38 [ТС] |
5 |
crou, новую тему тогда создавайте, т.к. у вас теперь другая задача, которая никак не связана с данной темой. создал, только модераторы вместо удаления/закрытия этой темы потерли, новую. Наверное здесь так принято, ок. Продолжаем разговор. Selection.Subtotal выдает «Метод завершен неверно», подозреваю что дело в привязке к БД. Как можно это обойти?
0 |
Скрипт 5471 / 1149 / 50 Регистрация: 15.09.2012 Сообщений: 3,515 |
||||
20.11.2012, 21:41 |
6 |
|||
crou, сколько столбцов вы копируете? Ваш код:
Девять столбцов есть в копируемом диапазоне?
0 |
0 / 0 / 0 Регистрация: 20.11.2012 Сообщений: 5 |
|
21.11.2012, 01:19 [ТС] |
7 |
Конечно есть, как я уже сказал в самом первом посте, приведенный там код под отладкой пошагово работал на все 100% (т.е. он копировал, вставлял и делал промежуточные суммы в столбцах 3, 8, 9 с группировкой по первому столбцу), но только пошагово, иначе выводил ошибку. После удаления строки Application.CutCopyMode = False, блок данных копируется всегда, но перестали строится промежуточные суммы как под отладкой так и без нее.
0 |
Скрипт 5471 / 1149 / 50 Регистрация: 15.09.2012 Сообщений: 3,515 |
||||
21.11.2012, 07:29 |
8 |
|||
crou,
0 |
0 / 0 / 0 Регистрация: 20.11.2012 Сообщений: 5 |
|
22.11.2012, 12:26 [ТС] |
9 |
1. просто данные (но они в свою очередь в exсel тянутся из sql сервера) я очень сильно подозреваю что это все связано с тем что данные тянутся из sql, как можно програмно сделать отключение таблицы от сервера ?
0 |
OlegSmirnov
Сообщение № 1
Группа: Пользователи Ранг: Участник Сообщений: 97
Замечаний: |
Здравствуйте.
Есть такой вопрос.
Макрос при вставке картинок на лист — выдает ошибку
«Run-time error ‘1004’ Метод Paste из класса Worksheet завершен неверно.»
И выделяет в коде слово «ActiveSheet.Paste».
Как это исправить ?
Код выглядит так:
[vba]
Код
Sub ВыводФотоФигур()
Dim itx As Long
Application.ScreenUpdating = False
For itx = ActiveSheet.Shapes.Count To 1 Step -1
If Not Intersect(ActiveSheet.Shapes(itx).TopLeftCell, Columns(«I:BJF»)) Is Nothing Then
ActiveSheet.Shapes(itx).Delete
End If
Next itx
ActiveSheet.Range(«I1:BJF50»).ClearContents
Dim Ws As Worksheet, i%, FR As Range, adr$, f$, a$, ms, str&, col&
str = 2: col = 9
For i = 5 To Cells(Rows.Count, 3).End(xlUp).Row
f = Cells(i, 3).Value
For Each Ws In Sheets
If Ws.Name <> «Поиск» And Ws.Name <> «Лист4» Then
Set FR = Ws.Cells.Find(f)
If Not FR Is Nothing Then
Cells(str, col) = Ws.Name & «!» & FR.Address
Cells(str + 1, col) = FR
Макрос1 Cells(str, col).Value, col
col = col + 4
‘adr = adr & » » & Ws.Name & «!» & FR.Address
‘—цикл по следующим найденным ячейкам
a = FR.Address ‘—запоминаем адрес первой найденной ячейки
Do
Set FR = Ws.Cells.FindNext(FR)
If FR.Address = a Then Exit Do
col = col + 4
Cells(str, col) = Ws.Name & «!» & FR.Address
Cells(str + 1, col) = FR
Макрос1 Cells(str, col).Value, col
‘adr = adr & » » & Ws.Name & «!» & FR.Address
Loop
‘————
End If
‘ If adr <> «» Then
‘ ms = Split(Mid(adr, 2, 1000))
‘ Cells(i, 5).Resize(, UBound(ms) + 1) = ms
‘ End If
End If
Next
‘Cells(i, 5) = adr ‘если в одну
‘если один адрес — одна ячейка
‘ms = Split(Mid(adr, 2, 1000))
‘Cells(i, 5).Resize(, UBound(ms) + 1) = ms
‘————————-
‘adr = «»
Next
Application.ScreenUpdating = True
Range(«A1»).Select
End Sub
Sub Макрос1(ByVal adr As String, ByVal col As Long)
‘adr = Лист5.[i2]
If adr = «» Then Exit Sub
shi = Split(adr, «!»)(0)
Mn = 0
Set cl = Range(adr) ‘[M16]
clleft = cl.Left: cltop = cl.Top
For Each Sh In Sheets(shi).Shapes
shLeft = Sh.Left
shtop = Sh.Top
d = (Abs(clleft — shLeft) ^ 2 + Abs(cltop — shtop) ^ 2) ^ 0.5
If Mn = 0 Then
Mn = d: f = Sh.Name
ElseIf Mn > d Then Mn = d: f = Sh.Name
End If
Next
Лист22.Cells(1, col) = f
Sheets(shi).Shapes(f).Copy ‘Select
Лист22.Cells(5, col).Select
ActiveSheet.Paste
End Sub
Sub ОчисткаДиапазона()
Dim itx As Long
Application.ScreenUpdating = False
For itx = ActiveSheet.Shapes.Count To 1 Step -1
If Not Intersect(ActiveSheet.Shapes(itx).TopLeftCell, Columns(«I:BJF»)) Is Nothing Then
ActiveSheet.Shapes(itx).Delete
End If
Next itx
ActiveSheet.Range(«I1:BJF50»).ClearContents
End Sub
[/vba]
Сообщение отредактировал OlegSmirnov — Вторник, 27.02.2018, 05:53
-
#2
I think you need to specify a Range to paste to e.g.:
Code:
ActiveSheet.Range("A1").Paste
Dom
Last edited: Apr 27, 2009
RoryA
MrExcel MVP, Moderator
-
#3
Where exactly is this code located? In a ThisWorkbook module or a worksheet module or a normal module?
-
#4
DOMSKI — The range didn’t make any difference, it still fell over at the same point, I had selected the range earlier in the code so it was already in the right place…..
RORYA — The code is in a module in the workbook…
Thanks guys…
Legacy 68668
Guest
-
#5
You can not use Paste method to a range
ActiveSheet.Range(«A1»).PasteSpecial
-
#6
Is the module named «Module1» or something else? Please could you indicate exactly which line the error occurs at
-
#7
SEIYA — Tried your code line, it still failed at that same point, i.e. when pasting….
RICHARDSCHOLLAR — It is «Module3» and the macro is called «CollateProgrammeReport()»
It fails at the following line…
Code:
Application.Run "'Milestones_matrix.xls'!ResetFilters"
Range("A11").Select
Sheets("All Milestones").Select
Selection.AutoFilter Field:=18, Criteria1:="=1", Operator:=xlAnd
LR = Cells(65536, 3).End(xlUp).Row
If LR > 2 Then
Range("B3:M" & LR).SpecialCells(xlCellTypeVisible).Copy
Windows("Programme report template.xls").Activate
[COLOR=red][B][U]ActiveSheet.Paste
[/U][/B][/COLOR] Application.CutCopyMode = False
End If
ActiveSheet.Paste
Application.CutCopyMode = False
End If
-
#8
Is there an actual Worksheet active when the Paste code is activated? It couldn’t be a ChartSheet could it? You could avoid such a possibility by referencing the specific sheet you want to target eg:
Rich (BB code):
Sheets("YourSheetNameHere").Paste
Replace the bit in red with your sheet name.
-
#9
The line..
Code:
Windows("Programme report template.xls").Activate
..is just before the paste code so I assume this is enough to activate the file.
None of the options listed have worked, it just doesn’t seem to like the paste task at that point….as I mentioned, I ahve another piece of code which works and does the same thing in another file!!
-
#10
What’s the activecell in the destination worksheet when you paste the data? Have you tried to specifically target the cell in which to paste? Do you have any merged cells in the detsination worksheet?