| Номер ошибки: | Ошибка 3021 | |
| Название ошибки: | Microsoft Access Error 3021 | |
| Описание ошибки: | No current record. | |
| Разработчик: | Microsoft Corporation | |
| Программное обеспечение: | Microsoft Access | |
| Относится к: | Windows XP, Vista, 7, 8, 10, 11 |
Объяснение «Microsoft Access Error 3021»
«Microsoft Access Error 3021» также считается ошибкой во время выполнения (ошибкой). Когда дело доходит до программного обеспечения, как Microsoft Access, инженеры могут использовать различные инструменты, чтобы попытаться сорвать эти ошибки как можно скорее. Ошибки, такие как ошибка 3021, иногда удаляются из отчетов, оставляя проблему остается нерешенной в программном обеспечении.
Ошибка 3021 может столкнуться с пользователями Microsoft Access, если они регулярно используют программу, также рассматривается как «No current record.». Когда появится ошибка, пользователи компьютеров смогут уведомить разработчика о наличии ошибки 3021 через отчеты об ошибках. Затем Microsoft Corporation нужно будет исправить эти ошибки в главном исходном коде и предоставить модифицированную версию для загрузки. Эта ситуация происходит из-за обновления программного обеспечения Microsoft Access является одним из решений ошибок 3021 ошибок и других проблем.
Почему происходит ошибка времени выполнения 3021?
Сбой во время запуска Microsoft Access или во время выполнения, как правило, когда вы столкнетесь с «Microsoft Access Error 3021». Вот три наиболее заметные причины ошибки ошибки 3021 во время выполнения происходят:
Ошибка 3021 Crash — Ошибка 3021 остановит компьютер от выполнения обычной программной операции. Это происходит много, когда продукт (Microsoft Access) или компьютер не может обрабатывать уникальные входные данные.
Утечка памяти «Microsoft Access Error 3021» — последствия утечки памяти Microsoft Access связаны с неисправной операционной системой. Потенциальные триггеры могут быть «бесконечным циклом», или когда программа выполняет «цикл» или повторение снова и снова.
Ошибка 3021 Logic Error — Компьютерная система создает неверную информацию или дает другой результат, даже если входные данные являются точными. Обычные причины этой проблемы связаны с ошибками в обработке данных.
Большинство ошибок Microsoft Access Error 3021 являются результатом отсутствия или повреждения версии файла, установленного Microsoft Access. Как правило, решить проблему можно заменой файла Microsoft Corporation. Кроме того, некоторые ошибки Microsoft Access Error 3021 могут возникать по причине наличия неправильных ссылок на реестр. По этой причине для очистки недействительных записей рекомендуется выполнить сканирование реестра.
Распространенные сообщения об ошибках в Microsoft Access Error 3021
Обнаруженные проблемы Microsoft Access Error 3021 с Microsoft Access включают:
- «Ошибка программы Microsoft Access Error 3021. «
- «Ошибка программного обеспечения Win32: Microsoft Access Error 3021»
- «Microsoft Access Error 3021 должен быть закрыт. «
- «Файл Microsoft Access Error 3021 не найден.»
- «Microsoft Access Error 3021 не может быть найден. «
- «Проблема при запуске приложения: Microsoft Access Error 3021. «
- «Файл Microsoft Access Error 3021 не запущен.»
- «Ошибка Microsoft Access Error 3021. «
- «Ошибка пути программного обеспечения: Microsoft Access Error 3021. «
Обычно ошибки Microsoft Access Error 3021 с Microsoft Access возникают во время запуска или завершения работы, в то время как программы, связанные с Microsoft Access Error 3021, выполняются, или редко во время последовательности обновления ОС. Запись ошибок Microsoft Access Error 3021 внутри Microsoft Access имеет решающее значение для обнаружения неисправностей электронной Windows и ретрансляции обратно в Microsoft Corporation для параметров ремонта.
Создатели Microsoft Access Error 3021 Трудности
Проблемы Microsoft Access Error 3021 могут быть отнесены к поврежденным или отсутствующим файлам, содержащим ошибки записям реестра, связанным с Microsoft Access Error 3021, или к вирусам / вредоносному ПО.
В частности, проблемы с Microsoft Access Error 3021, вызванные:
- Недопустимый Microsoft Access Error 3021 или поврежденный раздел реестра.
- Вирус или вредоносное ПО, повреждающее Microsoft Access Error 3021.
- Microsoft Access Error 3021 ошибочно удален или злонамеренно программным обеспечением, не связанным с приложением Microsoft Access.
- Microsoft Access Error 3021 конфликтует с другой программой (общим файлом).
- Microsoft Access (Microsoft Access Error 3021) поврежден во время загрузки или установки.
Продукт Solvusoft
Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.
Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11
Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление
Содержание
- Как исправить время выполнения Ошибка 3021 Ошибка Microsoft Access 3021
- Vba runtime error 3021
- Answered by:
- Question
- Answers
- Thread: [RESOLVED] Run-Time Error ‘3021’ No Current Record Found
- [RESOLVED] Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
- Re: Run-Time Error ‘3021’ No Current Record Found
Как исправить время выполнения Ошибка 3021 Ошибка Microsoft Access 3021
В этой статье представлена ошибка с номером Ошибка 3021, известная как Ошибка Microsoft Access 3021, описанная как Текущих записей нет.
Информация об ошибке
Имя ошибки: Ошибка Microsoft Access 3021
Номер ошибки: Ошибка 3021
Описание: Текущих записей нет.
Программное обеспечение: Microsoft Access
Разработчик: Microsoft
Этот инструмент исправления может устранить такие распространенные компьютерные ошибки, как BSODs, зависание системы и сбои. Он может заменить отсутствующие файлы операционной системы и библиотеки DLL, удалить вредоносное ПО и устранить вызванные им повреждения, а также оптимизировать ваш компьютер для максимальной производительности.
О программе Runtime Ошибка 3021
Время выполнения Ошибка 3021 происходит, когда Microsoft Access дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.
Определения (Бета)
Здесь мы приводим некоторые определения слов, содержащихся в вашей ошибке, в попытке помочь вам понять вашу проблему. Эта работа продолжается, поэтому иногда мы можем неправильно определить слово, так что не стесняйтесь пропустить этот раздел!
- Доступ — НЕ ИСПОЛЬЗУЙТЕ этот тег для Microsoft Access, используйте вместо него [ms-access]
- Запись — запись в программирование — это тип данных с метками для доступа к полям записи.
- Access . Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft, которая обычно объединяет реляционный Microsoft JetACE Database Engine с графическим пользовательским интерфейсом и инструментами разработки программного обеспечения.
- Microsoft Access — Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft который обычно сочетает в себе реляционное ядро СУБД Microsoft JetACE с графическим пользовательским интерфейсом и инструментами разработки программного обеспечения.
Симптомы Ошибка 3021 — Ошибка Microsoft Access 3021
Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.
Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.
(Ошибка Microsoft Access 3021) Repair Tool»/>
(Только для примера)
Причины Ошибка Microsoft Access 3021 — Ошибка 3021
При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.
Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.
Методы исправления
Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.
Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.
Источник
Vba runtime error 3021
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:

Question


Run-time Error 3021: No Current Record
I get this error while I try to Import Excel file in one of the MS Access tables using VBA. Attaching screenshot, how to solve this please??
Just to be clear, I’ve made sure «tblBoQ» table and «C:ImportBoQ» Excel files are at place. So there’s no question about it.
Answers


>>>. but now when I split the table in a FE/BE scenario, it gives me below error. Why is it so please??
According to your description, I have reproduced this issue. Regarding this issue, based on my research, two main reasons for the occurrence of the above error message are discussed below:
1. Appending of the records that were the primary key values
2. Violating referential integrity rules for a relationship defined between tables
You could use Get External Data wizard to import Excel file, after you have completed the Import wizard, Access notifies you of any problems that might have occurred during the import process. In some cases, Access might create a new table called ImportErrors, which contains any data that it was unable to import successfully. You can examine the data in this table to try to find out why the data did not import correctly.
For more information, click here to refer about Introduction to importing and exporting data
Источник
Thread: [RESOLVED] Run-Time Error ‘3021’ No Current Record Found
Thread Tools
Display
[RESOLVED] Run-Time Error ‘3021’ No Current Record Found
I’ve read through the other threads on this topic but they don’t seem to apply to my problem. I have a 1 row table that I’m trying to read into a recordset using VB6, but when I try to access any of the fields in the record, I get a runtime error 3021 «No current record».
I thought that when you use the Set Recordset command the recordset is populated with the contents of the target table. But that’s not happening. Can someone tell me what I’m doing wrong? Any help is greatly appreciated. Here’s my code:
Database: MS Access
Field: mpSalesRankTier1
Data type: Number
Content: 10000
Number of rows in table: 1
Last edited by vb6coder14; Oct 20th, 2014 at 01:03 PM .
Re: Run-Time Error ‘3021’ No Current Record Found
It looks like you are using DAO
Then:
1 Reference the DAO library
2 Change the lines where you declare and where you open Recordset
. If your problem is fixed don’t forget to mark your threads as resolved
using the Thread Tools menu .
Re: Run-Time Error ‘3021’ No Current Record Found
jggtz, I made all of the changes you suggested and no dice. I’m still getting the same problem.
Re: Run-Time Error ‘3021’ No Current Record Found
I happen to still use the DAO often. vb6coder14, with the DAO, it’s possible to have the recordset sitting on a non-record, and that’s exactly the case when you initially open a recordset.
All that’s necessary is that you execute a rsCtrlRec.MoveFirst command before you try and read the fields.
Be careful though. That will also throw an error if there are no records in the table. If you also want to avoid that, do something like «If rsCtrlRec.RecordCount > 0 Then . «
Re: Run-Time Error ‘3021’ No Current Record Found
It’s been a while since I have done DAO, so these are only observations, but here it goes..
1- dim rsCtrlRec as RecordSet is valid if your DAO reference is set correctly. (no need for DAO.)
2- Set rsCtrlRec = dbCtrlRec.OpenRecordset(«SYS_CONTROL_RECORD») is ok too
3- I always use indexed recordset, and by habit, I always include the line :
to avoid BOF conditions
4- Make sure you have records :
5- check the position of the record pointer with rsCtrlRec.BOF and rsCtrlRec.EOF when encountering problems such as you have. For example, if you have no records, after opening the recordset :
rsCtrlRec.MoveFirst
if rsCtrlRec.BOF then
rem there are no records
end if
6- and last, but it should have been the first point mentioned, are you sure there is not typo in your field name, and that the field indeed does exist.. you can get the value of a field by its index number instead of a literal
will return the value for the first field in the table, no matter what it’s literal name is. this will also indicate that you have indeed at least one field defined if no error is returned.
Re: Run-Time Error ‘3021’ No Current Record Found
Navion, you can use .MoveFirst, .MoveNext, .MovePrev, and .MoveLast without an index. There’s just no guarantee of the order of the records.
With no index, you just don’t get the use of .Seek. which is where the real power is.
Re: Run-Time Error ‘3021’ No Current Record Found
vb6coder14, here’s the DAO help file, in case you don’t have it. As Navion hinted, also be sure to learn the meaning of .BOF and .EOF. If you’re just using an .MDB style database, I’ve found the DAO to be an incredibly powerful tool. Elegant, bulletproof, and simple.
Re: Run-Time Error ‘3021’ No Current Record Found
Yeah sure. Except for a generic SQL handler program I have written way back then (i still use it and it never required any updating ever since) that used non indexed tables, all the rest of my work uses indexes and since my code rarely fails if ever , I keep methods that have proven their worth , even if things could be done some other ways.
Old habits die hard. For example, I never use :
Dim a as String
It will always be
for me although I am not real strong on Option Explicit
why bother and be nagged countless times. I can keep track of variables on my own loll
When you put too much restrictions on coding, it becomes VB 2010 and I don’t wish that anyone 
Re: Run-Time Error ‘3021’ No Current Record Found
Hey Navion, I’m totally with you. I mostly work alone these days, but I’ve had to fire programmers in the past who wouldn’t leave unbroken code alone. If it ain’t broke, DON’T FIX IT! There’s another «code sharing» thread on here where I made a similar point. The sharing of .BAS (or other) files in multiple .VBP project is a monumentally bad idea in my opinion. It’s the same issue, someone «fixing» code for one project that breaks another.
I’ll have to admit that I go back to the a!, a$, and a# days, but I have managed to wean myself into the new «as string» etc format. The only similar habit that I won’t break is Left$(s, 4), Mid$(s, 2, 5), etc. I do use variants and even like them, but I do stay away from them whenever possible. (Just noting that Left(s,4) returns a variant whereas Left$(s,4) returns a string.
Oh geez, I’m a HUGE advocate of Option Explicit. SOOO many times before we had it, I can remember beating my head against the wall, when it was just a variable name typo. In fact, I’ve long advocated that there should also be an Option TypeExplicit that applied to Redim as well as functions. I mean, if I want a variant or a late bound object, I’ll declare it as such.
I’ll agree that they should stay the meta-commands (Option . ), but they do make finding bugs easier.
Re: Run-Time Error ‘3021’ No Current Record Found
Its been a while since I have used DAO but I do not remember ever needing to issue a movefirst to get to an active record when a recordset is first opened.
Of course there is no code there that checks to see if any records were returned so my guess would be that movefirst would also throw an error as I suspect the problem is that the recordset is empty
Re: Run-Time Error ‘3021’ No Current Record Found
You know what, DataMiser? You’re right. I guess I’ve just never thought to NOT do a .MoveFirst. I just tested it and the recordset opens on the first record. Actually, all of my tables DO have indices (including PrimaryKey indices), so I’m not sure what happens on tables without an index, but that’s interesting.
Re: Run-Time Error ‘3021’ No Current Record Found
I do not think the presence of or absence of indexes/primary keys would have any effect either.
They will of course make your queries faster when using criteria that is indexed but as far as moving next, previous, first, last I would not expect there to be any difference.
Re: Run-Time Error ‘3021’ No Current Record Found
DataMiser is right. The recordset is empty. What threw me was my lack of understanding of the internal workings of a .MDB file. I actually manually keyed values into the database, but I didn’t hit the ENTER key. I went straight to SAVE. Consequently, although it appeared as if I had data, I really didn’t.
It wasn’t until I physically went back into the database and hit the ENTER key when a 2nd record appeared, this one prefixed with an ‘*’. I’m going to assume that’s the EOF pointer. When I ran my code again, it worked just fine.
Can someone confirm my interpretation of what happened, or am I still off base in my understanding?
Re: Run-Time Error ‘3021’ No Current Record Found
I wrote a paper back in the early days of VB, when they introduced Variants as the default data , destroying old myths and urban legends about stronger typed variables from old time programmers (although I am one of those myself). I do like variants but I use Typed variables too a lot, most often than not actually.
At some point, I got a bit lazy and started to use the variant versions of the common string functions too. but not anymore. they are slower and introduce an element of uncertainty (in my mind anyway, no real rationale on that argument). I reverted back to the mid$ and Trim$ etc. I think readability is much improved.
I have read your posts these past few days, and between the lines too. I think we both would get along 
Re: Run-Time Error ‘3021’ No Current Record Found
Before a MoveFirst is called, shouldn’t the recordset be checked for .EOF? I see that the posted code is using the generic ON ERROR GOTO [label], but checking for .EOF after returning the recordset can allow the option of using some default values vs. exiting the routine if .MoveFirst cause an error. Just thinking out loud
Insomnia is just a byproduct of, » It can’t be done»
Classics Enthusiast ? Here’s my 1969 Mustang Mach I Fastback. Her sister ’67 Coupe has been adopted
Re: Run-Time Error ‘3021’ No Current Record Found
Yep, you’re right LaVolpe, but that’s why I mentioned the RecordCount property in post #4. If it’s got records, a MoveFirst will never fail.
And a smile and nod to Navion.
)) Are we all having fun now? LMAO
Re: Run-Time Error ‘3021’ No Current Record Found
A recordset, depending on type & sql provider, can have an initial value of -1 if I recall correctly
Insomnia is just a byproduct of, » It can’t be done»
Classics Enthusiast ? Here’s my 1969 Mustang Mach I Fastback. Her sister ’67 Coupe has been adopted
Re: Run-Time Error ‘3021’ No Current Record Found
Yes, but for my own common use, I use indexed tables, a movefirst (that I don’t remember throwing an error on empty recordset), followed by a seek and a NoMatch that will take care of the EOF if any. Navigating down, of course, checking EOF is required.
On error should not be really be used doing DAO, good coding should use BOF, EOF, NoMatch (index stuff). That does not leave much causes for errors
Re: Run-Time Error ‘3021’ No Current Record Found
Indeed Elroy! Indeed! Almost a chat room atmosphere. But let’s not hijack the OP’s thread too much
(for the record lolll)
Re: Run-Time Error ‘3021’ No Current Record Found
Navion, I totally agree. I have my share of On Error Resume Next, and On Error Goto . in my code, but I very seldom use it when using DAO methods. I either get it right, or I debug it.
Actually, I just looked around at some of my standard DAO procedures and did find this code:
I did put error ignoring in there, but, truth be told, I’ve now got no idea why. However, going back to something I said earlier today, if it ain’t broken, don’t fix it.
Re: Run-Time Error ‘3021’ No Current Record Found
Honestly, don’t mess with DAO much any longer, but with ADO. Per MSDN: «A call to either MoveFirst or MoveLast when the Recordset is empty (both BOF and EOF are True) generates an error.»
To avoid that situation, my general iteration of the recordset kinda looks like this
Insomnia is just a byproduct of, » It can’t be done»
Classics Enthusiast ? Here’s my 1969 Mustang Mach I Fastback. Her sister ’67 Coupe has been adopted
Re: Run-Time Error ‘3021’ No Current Record Found
Yep, I seldom let these conditions happen, but I believe that an empty recordset will set both .BOF and .EOF as true. And I think that’s the only time it happens. Also, I’m pretty sure that the DAO and the ADO are VERY similar (if not identical) regarding all of these relatively straightforward procedures.
Re: Run-Time Error ‘3021’ No Current Record Found
Funny that you should mention that Elroy, I forgot to do it myself. another essential of DAO is IsNull, particularly with binary fields, they don’t like much being cast to empty strings, although .FieldSize does the job too.
Re: Run-Time Error ‘3021’ No Current Record Found
Yes, .Recordcount will return -1 in cases where recordcount is not supported. I can’t remember if this is the case with DAO but ADO will return -1 when using a server side cursor no matter how many records there may be.
Checking for .eof is a more fool proof method.
Re: Run-Time Error ‘3021’ No Current Record Found
When using DAO .RecordCount will give you the result only after a .MoveLast method
. If your problem is fixed don’t forget to mark your threads as resolved
using the Thread Tools menu .
Источник
- Remove From My Forums
-
General discussion
-
Yes it matters.
And it is not only a programmers fault.
Once again I had this problem today :- deleted all records in a subform
- jumped to another record in mainform
- because of a couple of conditions most controls in the subform were disabled (via VBA)
- additional AllowAdditions and AllowEdits in the subform were set to FALSE (via VBA)
- Access showed Error 3021
The workarround for this «special appearance» of error 3021 was :
- calling the Requery() — method of the subform after disabling controls and setting Allow—-props.
additional remarks :
- The error only shows up if I delete the records before
- the subform is linked via Masterfields/Childfields
Best regards,
dp.dedicated to all victims of 3021
-
Edited by
Wednesday, May 8, 2013 8:25 AM
- Remove From My Forums
-
General discussion
-
Yes it matters.
And it is not only a programmers fault.
Once again I had this problem today :- deleted all records in a subform
- jumped to another record in mainform
- because of a couple of conditions most controls in the subform were disabled (via VBA)
- additional AllowAdditions and AllowEdits in the subform were set to FALSE (via VBA)
- Access showed Error 3021
The workarround for this «special appearance» of error 3021 was :
- calling the Requery() — method of the subform after disabling controls and setting Allow—-props.
additional remarks :
- The error only shows up if I delete the records before
- the subform is linked via Masterfields/Childfields
Best regards,
dp.dedicated to all victims of 3021
-
Edited by
Wednesday, May 8, 2013 8:25 AM
|
zvs 0 / 0 / 0 Регистрация: 04.11.2012 Сообщений: 56 |
||||
|
1 |
||||
|
10.12.2013, 16:03. Показов 4545. Ответов 5 Метки нет (Все метки)
Здравствуйте!
__________________
0 |
|
mobile
26771 / 14450 / 3192 Регистрация: 28.04.2012 Сообщений: 15,782 |
||||
|
10.12.2013, 16:44 |
2 |
|||
|
Все работает до тех пор пока на параметр-дату( D1)нет записи…ошибка-3021… Поскольку неясно куда надо переходить и в каком месте кода проверять отсутствие данных, то скажем так:
1 |
|
zvs 0 / 0 / 0 Регистрация: 04.11.2012 Сообщений: 56 |
||||
|
11.12.2013, 12:38 [ТС] |
3 |
|||
|
Поскольку неясно куда надо переходить и в каком месте кода проверять отсутствие данных, то скажем так:
У меня ошибка срабатывает на rst2.MoveFirst, посколко на дату D1(дата из формы) в запросе нет записей и естественно нет первой строки…., для этого случая мне нужно таблицу на дату D1 заполнить поля нулями….(таблица используется для отчета за период)…
0 |
|
mobile
26771 / 14450 / 3192 Регистрация: 28.04.2012 Сообщений: 15,782 |
||||
|
11.12.2013, 13:04 |
4 |
|||
|
У меня ошибка срабатывает на rst2.MoveFirst, посколко на дату D1(дата из формы) в запросе нет записей и естественно нет первой строки…., для этого случая мне нужно таблицу на дату D1 заполнить поля нулями Может быть так
0 |
|
Модератор
11261 / 4592 / 739 Регистрация: 07.08.2010 Сообщений: 13,156 Записей в блоге: 4 |
|
|
11.12.2013, 13:16 |
5 |
|
применяю только Do While rst2.EOF = False
0 |
|
zvs 0 / 0 / 0 Регистрация: 04.11.2012 Сообщений: 56 |
||||||||
|
11.12.2013, 15:51 [ТС] |
6 |
|||||||
|
Поскольку неясно куда надо переходить и в каком месте кода проверять отсутствие данных, то скажем так:
спасибо за подсказку, я ею воспользовалась…но у меня возникла другая проблема -Как правильно прописать повторяющуюся ошибку…Первый раз все правильно работает, а во второй раз не видит метки….
0 |
I am trying to export multiple datasets to the respective new Excel file.
Public Sub MultipleQueries()
Dim i As Integer
Dim Mailer As Database
Dim rs1 As Recordset
Dim rs2 As Recordset
Dim qdf As QueryDef
Set Mailer = CurrentDb
Set rs1 = Mailer.OpenRecordset("MailerData")
Set qdf = Mailer.CreateQueryDef("CCspl", "PARAMETERS CostCentre Text ( 255 );SELECT MonthlyFteData.CostCentre, MonthlyFteData.EmpName, MonthlyFteData.Workload FROM MonthlyFteData WHERE (((MonthlyFteData.CostCentre)=[CostCentre]))")
For i = 0 To rs1.RecordCount - 1
qdf.Parameters("CostCentre") = rs1.Fields("CostCentre")
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
Set oExcel = CreateObject("Excel.Application")
Set oBook = oExcel.Workbooks.Add
Set oSheet = oBook.Worksheets(1)
Set rs2 = qdf.OpenRecordset()
With rs2
oSheet.Range("A2").CopyFromRecordset rs2
oBook.SaveAs "C:Users807140Downloads" & rs2.Fields("CostCentre") & ".xlsx"
rs2.Close
oExcel.Quit
Set oExcel = Nothing
End With
rs1.MoveNext
Next i
qdf.Close
Set qdf = Nothing
rs1.Close
End Sub
But I get the Runtime Error 3021 — No Current Record
I substituted the
oSheet.Range("A2").CopyFromRecordset rs2
oBook.SaveAs "C:Users807140Downloads" & rs2.Fields("CostCentre") & ".xlsx"
with
Debug.Print .RecordCount
And I do actually get the appropriate record count for rs2.
How can I fix my code to eliminate the error?
asked Jul 28, 2016 at 16:27
2
Don’t use For..Next loops with Recordsets. Use this:
Do While Not rs1.EOF
' do stuff with rs1
rs1.MoveNext
Loop
rs1.close
And as Ryan wrote, Dim don’t belong into any loop, move them to the start of the sub.
If this doesn’t help, please tell us on which line the error occurs.
answered Jul 28, 2016 at 16:45
![]()
AndreAndre
25.9k6 gold badges34 silver badges78 bronze badges
1
The 3021 error («No current record.») occurs at the second of these two lines:
oSheet.Range("A2").CopyFromRecordset rs2
oBook.SaveAs "C:Users807140Downloads" & rs2.Fields("CostCentre") & ".xlsx"
That happens because the rs2 recordset pointer is at EOF after you do CopyFromRecordset rs2. Then at SaveAs, you ask for rs2.Fields("CostCentre"), but there is no available record («no current record») when the recordset pointer is at EOF.
However the rs1.Fields("CostCentre") value you used as the query parameter when opening rs2 is still accessible. So you can make the error go away by asking for rs1.Fields("CostCentre") instead of rs2.Fields("CostCentre")
oBook.SaveAs "C:Users807140Downloads" & rs1.Fields("CostCentre") & ".xlsx"
answered Jul 28, 2016 at 20:50
HansUpHansUp
95.3k11 gold badges74 silver badges135 bronze badges
1
This code has a few issues pointed out by @Andre and Ryan.
You’re not reusing your Excel object, you’re re-dimming objects that should only be defined once, using a With that never gets referenced so it just adds to code with no benefit.
You’re also creating a parameter query on the fly in code — instead of creating it in SQL and saving it to be reused by name.
You can try this rewritten code and see if it works better for you. I do believe that a predefined query is the better way to go — and then I’d close the query inside the loop and reset it at the start each time. I’ve just seen weird stuff happen when querydefs are reused inside loops without resetting them.
Anyways give this a try — and report on specific line that causes error
Public Sub MultipleQueries()
Dim i As Integer
Dim Mailer As Database
Dim rs1 As Recordset
Dim rs2 As Recordset
Dim qdf As QueryDef
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
' Only Open and Close Excel once
Set oExcel = CreateObject("Excel.Application")
Set Mailer = CurrentDb
Set rs1 = Mailer.OpenRecordset("MailerData")
' Ideally you'd put this create query ahead of time instead of dynamically
Set qdf = Mailer.CreateQueryDef("CCspl", "PARAMETERS CostCentre Text ( 255 );SELECT MonthlyFteData.CostCentre, MonthlyFteData.EmpName, MonthlyFteData.Workload FROM MonthlyFteData WHERE (((MonthlyFteData.CostCentre)=[CostCentre]))")
Do Until rs1.EOF
' Sometimes weird things happen when you reuse querydef with new parameters
qdf.Parameters("CostCentre") = rs1.Fields("CostCentre")
Set rs2 = qdf.OpenRecordset()
If Not rs2.EOF Then
Set oBook = oExcel.Workbooks.Add
Set oSheet = oBook.Worksheets(1)
oSheet.Range("A2").CopyFromRecordset rs2
oBook.SaveAs "C:Users807140Downloads" & rs2.Fields("CostCentre") & ".xlsx"
Else
Msgbox "No Data Found for: " & rs1.Fields("CostCentre")
Exit Do
End If
rs2.Close
Set rs2 = Nothing
Set oBook = Nothing
Set oSheet = Nothing
rs1.MoveNext
Loop
oExcel.Quit
qdf.Close
rs1.Close
Mailer.Close
Set qdf = Nothing
Set rs1 = Nothing
Set Mailer = Nothing
' Remove Excel references
Set oBook = Nothing
Set oSheet = Nothing
Set oExcel = Nothing
End Sub
answered Jul 28, 2016 at 17:09
![]()
dbmitchdbmitch
5,3534 gold badges23 silver badges38 bronze badges
7
Правила форума
Темы, в которых будет сначала написано «что нужно сделать», а затем просьба «помогите», будут закрыты.
Читайте требования к создаваемым темам.
- burik
- Постоялец

-
- Сообщения: 514
- Зарегистрирован: 03.11.2005 (Чт) 22:04
- Откуда: Беларусь, Рогачев
-
- ICQ
Ошибка 3021. Текущая запись отсутствует.
Здравствуйте!
Вобщем возникает ошибка 3021 (Текущая запись отсутствует).
Есть такой участок кода:
- Код: Выделить всё
For i = 1 To rs.RecordCount
Load Days(i)
With Days(i)
.Top = Days(i - 1).Top + Days(i - 1).Height + 60
.TDate = rs.Fields(1)
.Text = rs.Fields(3)
.BackColor = vbWhite
.Visible = True
End With
rs.MoveNext
Next i
Days — это массив моих контролов.
Ошибка возникает в …Property Let TDate.. :
- Код: Выделить всё
Public Property Let TDate(ByVal New_TDate As Variant)
DTPicker1.Value() = Mid$(New_TDate, 1, 10) '<<<<<<<< Здесь ошибка возникает
tTime(0).Text = IIf(Len(CStr(Hour(New_TDate))) = 1, "0" & CStr(Hour(New_TDate)), CStr(Hour(New_TDate)))
tTime(1).Text = IIf(Len(CStr(Minute(New_TDate))) = 1, "0" & CStr(Minute(New_TDate)), CStr(Minute(New_TDate)))
tTime(2).Text = IIf(Len(CStr(Second(New_TDate))) = 1, "0" & CStr(Second(New_TDate)), CStr(Second(New_TDate)))
PropertyChanged "TDate"
End Property
Кол-во записей в rs — 4 у всех fields(1) = «24.06.2007 11:30:25».
Вроде все проверил..
Не знаю где ошибка.. ![]()
Между слухов, сказок, мифов,
просто лжи, легенд сомнений
мы враждуем жарче скифов
за несходство заблуждений
Игорь Губерман
- Antonariy
- Повелитель Internet Explorer

-
- Сообщения: 4824
- Зарегистрирован: 28.04.2005 (Чт) 14:33
- Откуда: Мимо проходил
-
- ICQ
Antonariy » 25.06.2007 (Пн) 15:14
А ты там нигде DataField/DataSource не проставляешь? Такая ошибка возникает, когда присваивается значение контролу, связанному с полем рекордета, который находится в BOF/EOF.
Лучший способ понять что-то самому — объяснить это другому.
- burik
- Постоялец

-
- Сообщения: 514
- Зарегистрирован: 03.11.2005 (Чт) 22:04
- Откуда: Беларусь, Рогачев
-
- ICQ
burik » 25.06.2007 (Пн) 15:36
А ты там нигде DataField/DataSource не проставляешь? Такая ошибка возникает, когда присваивается значение контролу, связанному с полем рекордета, который находится в BOF/EOF.
Нет. Там только две процедуры с БД работают (эта и еще одна), обе такого типа:
- Код: Выделить всё
sub sub_name()
set db = dao.opendatabase..
set rs = db.opendatabase..
...
rs.close
set rs = nothing
db.close
set db = nothing
end sub
Связанных с БД контролов нет. В моем контроле есть DTPicker(календарь), image и два текст бокса
Между слухов, сказок, мифов,
просто лжи, легенд сомнений
мы враждуем жарче скифов
за несходство заблуждений
Игорь Губерман
- Antonariy
- Повелитель Internet Explorer

-
- Сообщения: 4824
- Зарегистрирован: 28.04.2005 (Чт) 14:33
- Откуда: Мимо проходил
-
- ICQ
Antonariy » 25.06.2007 (Пн) 15:51
Возможно рекордсет таки находится в EOF потому что For i = 1 To rs.RecordCount — безграмотно. Грамотно так:
- Код: Выделить всё
While Not rs.EOF
...
i = i + 1
rs.MoveNext
Wend
Кроме того ты передаешь rs.Fields(1) в функцию, которая принимает Variant. Из-за этого передается не значение свойства по умолчанию — Value, — а объект Field.
Лучший способ понять что-то самому — объяснить это другому.
- burik
- Постоялец

-
- Сообщения: 514
- Зарегистрирован: 03.11.2005 (Чт) 22:04
- Откуда: Беларусь, Рогачев
-
- ICQ
burik » 25.06.2007 (Пн) 16:00
Antonariy спасибо!
Заработало. ![]()
Между слухов, сказок, мифов,
просто лжи, легенд сомнений
мы враждуем жарче скифов
за несходство заблуждений
Игорь Губерман
Вернуться в Visual Basic 1–6
Кто сейчас на конференции
Сейчас этот форум просматривают: Yandex-бот и гости: 1
- Remove From My Forums
Updating recordset — error 3021 — no current record
-
Question
-
Fellow developers, I am using Access 2010
I inherited some code for in an existing app — for updating. Normally I write direct sql but current code is doing below. All of this in in Access 2010 vba. The mykeyid is captured after we do an insert to create a user records in the beginning of the app.
This has been working flawleslly for weeks — hit about 100 times per day without error.Here is the code
mysql = «Select * from myAgentTable where keyid =» & mykeyid
set myrs = mydb.openrecordset(mysql, dbopdbOpenDynaset)
With myrs
.Edit
.Fields(«EndDate»).Value =Now()End With
myrs.Update
myrs.closemydb.close
This code has been working flawlessly for weeks. Today, I saw too cases where my error handler bubled up a 3021. No current record. And that is pretty much impossible. When the app opens we insert the record for the key, when they close we update that
record using the identity value key. There record IS in the db. I have solid error handles on «every» db call.Is there something wrong with they type of recordset we are using for this or is there another locking option we could try. As you know, finding somethign that happens rarely is very difficult becasue we cannot get this to happen all of the time.
Thanks for any suggestions.
MG
Answers
-
Hi Celieste,
It has not occurred since, we have additional traps put in to see if the values is coming back as zero. So far, nothing yet.
-
Proposed as answer by
Tuesday, September 6, 2016 1:19 AM
-
Marked as answer by
Chenchen Li
Wednesday, September 7, 2016 5:43 PM
-
Proposed as answer by
