The following VBA code (Excel 2007) is failing with Error 1004, «Autofill Method of Range Class Failed.». Can anyone tell me how to fix it?
Dim src As Range, out As Range, wks As Worksheet
Set wks = Me
Set out = wks.Range("B:U")
Set src = wks.Range("A6")
src.AutoFill Destination:=out
(note: I have Googled, etc. for this. It comes up fairly often, but all of the responses that I saw had to do with malformed range addresses, which AFAIK is not my problem.
At someone’s suggestion I tried replacing the autofill line with the following:
src.Copy out
This had the effect of throwing my Excel session into an apparent infinite loop consuming 100% CPU and then just hanging forever.
OK, apparently the source has to be part of the destination range for autofill. So my code now looks like this:
Dim src As Range, out As Range, wks As Worksheet
Set wks = Me
Set out = wks.Range("B1")
Set src = wks.Range("A6")
src.Copy out
Set out = wks.Range("B:U")
Set src = wks.Range("B1")
src.AutoFill Destination:=out, Type:=xlFillCopy
Same error on the last line.
Djenkinss Пользователь Сообщений: 23 |
#1 30.04.2021 10:11:43 Всем доброго дня! в VBA чайник, но набросал код. Его смысл — заполнить 28 ячеек формулами ячейка=ячейка, далее он протягивает данный код на весь необходимый диапазон создаваемой таблицы. Ошибка возникает в строке
заранее признателен! |
||
Дмитрий(The_Prist) Щербаков Пользователь Сообщений: 14264 Профессиональная разработка приложений для MS Office |
#2 30.04.2021 10:19:43 Вам сюда: Как обратиться к диапазону из VBA читать внимательно и вдумчиво.
Для Range Вы указали явно лист, а для Cells — нет. Отсюда и ошибка. Также, кстати, ошибка может быть и из-за некорректного значения в переменной Endrow. Проверьте что в ней на момент ошибки. Изменено: Дмитрий(The_Prist) Щербаков — 30.04.2021 10:21:09 Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы… |
||
можно с первого раза или бесконечно долго пытаться угадать в чем причина, а можно отрыть файл, посмотреть и сказать Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
|
Djenkinss Пользователь Сообщений: 23 |
Простите, файл приложил. там «Кнопка 6» на листе «Приложение 1 к заявлению» 3ю кнопку в Userform1 можно не нажимать, пока там ничего не писал. Прикрепленные файлы
|
Djenkinss Пользователь Сообщений: 23 |
#5 30.04.2021 11:46:01
Дмитрий, спасибо за статью, очень много полезных подсказок. Для Cells попытался также указать какой лист активен — не помогло. голову сломал откуда эта ошибка «Метод AutoFill из класса Range завершен неверно» |
||
Mershik Пользователь Сообщений: 8277 |
#6 30.04.2021 12:06:02 Djenkinss, может так?
Не бойтесь совершенства. Вам его не достичь. |
||
Djenkinss Пользователь Сообщений: 23 |
#7 30.04.2021 12:15:21 Mershik
!!!! большое спасибо!! Даже когда Дмитрий(The_Prist) Щербаков написал часть кода без .FillDown.. Еще раз ОГРОМНОЕ СПАСИБО! |
Группа: Пользователи Ранг: Прохожий Сообщений: 2
Замечаний: |
Помогите, пожалуйста. Записывала макрос именно с помощью записи макроса. При выполнении макрос выдает ошибку Run-time error ‘1004’: Метод Autofill из класса Range завершен неверно. Ругается на строчку Selection.AutoFill Destination:=Range(«I2:I9806»)
[vba]
Код
Cells.Select
Selection.Replace What:=»0″, Replacement:=»», LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Selection.Replace What:=»н/с», Replacement:=»», LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
ActiveWindow.ScrollColumn = 33
ActiveWindow.ScrollColumn = 26
ActiveWindow.SmallScroll Down:=57
ActiveWindow.ScrollRow = 2915
Selection.Replace What:=»00.01.1900″, Replacement:=»», LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
ActiveWindow.ScrollRow = 1
Range(«AJ7»).Select
ActiveWindow.ScrollColumn = 1
ActiveWindow.ScrollColumn = 20
Range(«Z2»).Select
ActiveWindow.ScrollColumn = 1
Range(«D2»).Select
ActiveCell.FormulaR1C1 = «=VLOOKUP(RC[-2],’коды ТНВЭД’!R2C1:R3911C2,2,0)»
Selection.AutoFill Destination:=Range(«D2:D10806»)
Range(«D2:D10806»).Select
Range(«P2»).Select
ActiveCell.FormulaR1C1 = «=VLOOKUP(RC[-1],страны!R2C1:R256C2,2,0)»
Selection.AutoFill Destination:=Range(«P2:P10806»)
Range(«P2:P10806»).Select
ActiveWindow.ScrollColumn = 12
ActiveWindow.ScrollColumn = 29
Range(«AL2»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[-1]=0,»»С»»)»
Range(«AL2»).Select
Selection.ClearContents
Range(«AL2»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[-1]=0,»»С»»,0)»
Columns(«AK:AK»).Select
Selection.Replace What:=»0″, Replacement:=»», LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range(«AL2»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[-1]=0,»»С»»,0)»
Range(«AL2»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[-1]>0,0,»»С»»)»
Range(«AK2»).Select
ActiveCell.FormulaR1C1 = «1/0/1900»
Range(«AK2»).Select
Selection.Copy
Range(«AL2»).Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = «=IF(RC[-1]>0,0,»»С»»)»
Range(«AK2»).Select
Selection.ClearContents
Range(«AL2»).Select
Selection.ClearContents
Range(«AL2»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[-3]=0,»»С»»)»
Selection.AutoFill Destination:=Range(«AL2:AL10806»)
Range(«AL2:AL10806»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[-3]=0,»»С»»,»»0″»)»
Range(«AL2»).Select
Selection.AutoFill Destination:=Range(«AL2:AL10806»)
Range(«AL2:AL10806»).Select
Range(«AL15»).Select
ActiveWindow.ScrollColumn = 1
Range(«A2»).Select
ActiveCell.FormulaR1C1 = «=1»
Range(«V2»).Select
ActiveCell.FormulaR1C1 = «=1»
Range(«A3»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[17]=0,R[-1]C,R[-1]C+1)»
Selection.AutoFill Destination:=Range(«A3:A10806»)
Range(«A3:A10806»).Select
Range(«V3»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[-4]=0,R[-1]C+1,1)»
Selection.AutoFill Destination:=Range(«V3:V10806»)
Range(«V3:V10806»).Select
ActiveWindow.ScrollRow = 1
Range(«Z2:AA2»).Select
Selection.AutoFill Destination:=Range(«Z2:AA10806»)
Range(«Z2:AA703»).Select
Range(«AF2»).Select
Selection.AutoFill Destination:=Range(«AF2:AF10806»)
Range(«AF2:AF703»).Select
ActiveWindow.SmallScroll Down:=276
ActiveWindow.ScrollRow = 647
ActiveWindow.SmallScroll Down:=45
ActiveWindow.ScrollRow = 7717
ActiveWindow.ScrollRow = 1
ActiveWindow.SmallScroll ToRight:=11
Range(«AM2»).Select
ActiveCell.FormulaR1C1 = «=VLOOKUP(RC[-14],ТРОИС!R1C1:R2138C5,2,0)»
Range(«AN2»).Select
ActiveCell.FormulaR1C1 = «=VLOOKUP(RC[-15],ТРОИС!R1C1:R2126C5,3,0)»
Range(«AO2»).Select
ActiveCell.FormulaR1C1 = «=VLOOKUP(RC[-16],ТРОИС!R2C1:R2412C4,4,0)»
Range(«AM2:AO2»).Select
Selection.AutoFill Destination:=Range(«AM2:AO10806»)
Range(«AM2:AO703»).Select
ActiveWindow.ScrollRow = 2190
ActiveWindow.SmallScroll Down:=-60
ActiveWindow.ScrollRow = 647
ActiveWindow.SmallScroll Down:=-114
ActiveWindow.ScrollRow = 1
Range(«AI2»).Select
ActiveWindow.ScrollColumn = 2
Columns(«AM:AO»).Select
ActiveWorkbook.Save
Columns(«AM:AO»).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
xlNone, SkipBlanks:=False, Transpose:=False
Selection.Replace What:=»#?/?», Replacement:=»», LookAt:=xlWhole, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range(«AN10»).Select
Range(«G3»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[-6]=R[-1]C[-6],,1)»
Selection.AutoFill Destination:=Range(«G3:G10806»)
Range(«G3:G10806»).Select
Range(«H3»).Select
ActiveCell.FormulaR1C1 = «=IF(RC[-7]=R[-1]C[-7],,»»PK»»)»
Selection.AutoFill Destination:=Range(«H3:H10806»)
Range(«H3:H10806»).Select
Columns(«G:H»).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Replace What:=»0″, Replacement:=»», LookAt:=xlWhole, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range(«AH2»).Select
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = «=IF(RC[1]=0,,»»‘01401″»)»
ActiveCell.FormulaR1C1 = «=IF(RC[1]=0,,»»01401″»)»
Range(«AH2»).Select
Selection.AutoFill Destination:=Range(«AH2:AH10806»)
Range(«AH2:AH10806»).Select
Columns(«AH:AH»).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Replace What:=»0″, Replacement:=»», LookAt:=xlWhole, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Columns(«AL:AL»).Select
Selection.Replace What:=»0″, Replacement:=»», LookAt:=xlWhole, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Selection.Find(What:=»0″, After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase _
:=False, SearchFormat:=False).Activate
Selection.Replace What:=»0″, Replacement:=»», LookAt:=xlWhole, _
SearchOrder:=xlByColumns, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range(«AI11»).Select
ActiveWindow.SmallScroll Down:=147
ActiveWindow.ScrollRow = 7950
ActiveWindow.SmallScroll Down:=-18
ActiveWindow.ScrollRow = 1
Range(«AK6»).Select
ActiveWindow.ScrollColumn = 1
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = «=IF(RC[-8]=R[-1]C[-8],»»»»,RC[-4])»
Selection.AutoFill Destination:=Range(«I2:I10806»)
Range(«I2:I10806»).Select
End Sub
[/vba]
При чем, если вот эту часть вынести в отдельный макрос, то ошибка не выскакивает
[vba]
Код
Application.CutCopyMode = False
ActiveCell.FormulaR1C1 = «=IF(RC[-8]=R[-1]C[-8],»»»»,RC[-4])»
Selection.AutoFill Destination:=Range(«I2:I10806»)
Range(«I2:I10806»).Select
[/vba]
Сообщение отредактировал GalinaS — Вторник, 28.02.2023, 15:23
BSH 17 / 1 / 2 Регистрация: 20.04.2016 Сообщений: 120 |
||||||||
1 |
||||||||
30.03.2017, 20:53. Показов 5205. Ответов 2 Метки нет (Все метки)
Добрый вечер.
Но когда нужно протащить ее вниз пишет ошибку «Метод AutoFill из класса Range завершён неверно»,
Потому, что формула всегда прописывается в следующую ячейку. И так каждый раз когда выгружаешь данные.
0 |
5 / 5 / 5 Регистрация: 03.03.2011 Сообщений: 43 |
|
31.03.2017, 10:59 |
2 |
«=VLOOKUP(R3C1,[» & Format(Date, «ddmmyy») & «.XLSX]Sheet1!C1:C4,4,0)» А книга с именем «[» & Format(Date, «ddmmyy») & «.XLSX]» при этом существует и открыта?
0 |
BSH 17 / 1 / 2 Регистрация: 20.04.2016 Сообщений: 120 |
||||
31.03.2017, 13:04 [ТС] |
3 |
|||
Да открыта и существует. Проблема в том что каждый день столбец где будет прописываться «=VLOOKUP()», будет меняться. И нужно, что бы формула протягивалась вниз. каждый раз в новой строчке.
0 |
Solution 1
From MSDN:
The destination must include the
source range.
B:U
does not contain A6
and thus there is an error. I believe that you probably want out
to be set to A6:U6
.
Specifiying just the column name means that you want to fill every row in that column which is unlikely to be the desired behvaiour
Update
Further to the OP’s comment below and update to the original answer, this might do the trick:
Dim src As Range, out As Range, wks As Worksheet
Set wks = Me
Set out = wks.Range("B1")
Set src = wks.Range("A6")
src.Copy out
Set out = wks.Range("B1:U1")
Set src = wks.Range("B1")
src.AutoFill Destination:=out, Type:=xlFillCopy
Set out = wks.Range("B:U")
Set src = wks.Range("B1:U1")
src.AutoFill Destination:=out, Type:=xlFillCopy
AutoFill
is constrained to a single direction (i.e. horizontal or vertical) at once. To fill a two-dimensional area from a single cell you first have to auto-fill a line along one edge of that area and then stretch that line across the area
For the specific case of copying the formatting and clearing the contents (by virtue of the source cell being empty), this is better:
Dim src As Range, out As Range, wks As Worksheet
Set wks = Sheet1
Set out = wks.Range("B:U")
Set src = wks.Range("A6")
src.Copy out
Solution 2
To make AutoFill
work, you need to make the range of AutoFill
more than the source range. If the AutoFill range is same as of Source range then there is nothing to AutoFill in that range and hence you would get an error
1004: AutoFill method of Range class failed.
So make AutoFill range more than the source range and error will gone.
Related videos on Youtube
15 : 11
Excel VBA — Drag Down Formula (Autofill) to Last Row of Data — Part 6
Learn Google Spreadsheets
10 : 18
Autofill using VBA Code — Autofill Formula down
02 : 57
AutoFill Formula To The Last Used Row || Advanced Excel || Excel VBA || When ExcelisAdvanceD
06 : 07
Auto Fill Table Data Gaps Excel VBA Macro
19 : 15
Excel VBA: Referring to Ranges & Writing to Cells (Range, Cells, Offset, Names)
10 : 07
Episode #7 — Excel VBA Autofill Method: Because copying and pasting is so lame
Visually Basic EXCELlent Tips and Tricks
05 : 41
How to Fix VBA Run-time error ‘1004’ — Excel VBA Tutorial
09 : 20
How to Solve a VBA Error in Less Than a Minute
02 : 02
VB.NET — Excel — How to fix error — Select Method of range class failed
Comments
-
The following VBA code (Excel 2007) is failing with Error 1004, «Autofill Method of Range Class Failed.». Can anyone tell me how to fix it?
Dim src As Range, out As Range, wks As Worksheet Set wks = Me Set out = wks.Range("B:U") Set src = wks.Range("A6") src.AutoFill Destination:=out
(note: I have Googled, etc. for this. It comes up fairly often, but all of the responses that I saw had to do with malformed range addresses, which AFAIK is not my problem.
At someone’s suggestion I tried replacing the autofill line with the following:
src.Copy out
This had the effect of throwing my Excel session into an apparent infinite loop consuming 100% CPU and then just hanging forever.
OK, apparently the source has to be part of the destination range for autofill. So my code now looks like this:
Dim src As Range, out As Range, wks As Worksheet Set wks = Me Set out = wks.Range("B1") Set src = wks.Range("A6") src.Copy out Set out = wks.Range("B:U") Set src = wks.Range("B1") src.AutoFill Destination:=out, Type:=xlFillCopy
Same error on the last line.
-
How does this differ from what I am doing?
-
Actually, I am trying to reset the formating(to whats in A6) and clear the contents for all rows in that column range. This works fine when I do it manually.
-
Thanks, but that was not the problem in this case. You will note from my code that the source was one cell, whereas the out range was several columns.