Access ошибка 3021

Yes it matters. And it is not only a programmers fault. Once again I had this problem today :
  • 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

Icon Ex Номер ошибки: Ошибка 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) | Лицензия | Политика защиты личных сведений | Условия | Удаление

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?

Community's user avatar

asked Jul 28, 2016 at 16:27

Eliseo Di Folco's user avatar

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

Andre's user avatar

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

HansUp's user avatar

HansUpHansUp

95.4k11 gold badges75 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

dbmitch's user avatar

dbmitchdbmitch

5,3534 gold badges23 silver badges38 bronze badges

7

zvs

0 / 0 / 0

Регистрация: 04.11.2012

Сообщений: 56

1

10.12.2013, 16:03. Показов 4582. Ответов 5

Метки нет (Все метки)


Здравствуйте!
Моя программа записывает данные в таблицу исходя из запроса с параметрами. Все работает до тех пор пока на параметр-дату( D1)нет записи…ошибка-3021…
Мне нужно при этой ошибке в таблицу rst.Fields(2)…rst.Fields(12) прописать 0 и перейти к следующей процедуре…
Часть програмы

QBasic/QuickBASIC
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
gl = "qrtGL1VALL"
    Set zap1 = DB.QueryDefs(gl)
    
        IF NOT rst2.BOF THEN
        rst2.MoveFirst
        
          DO UNTIL rst2.EOF
         IF rst2![P] = -1 THEN
        S = rst2![ICCODE]
     
    zap1.Parameters("Par1") = D1
    zap1.Parameters("Par2") = "P"
    zap1.Parameters("Par3") = S
    zap1.Parameters("Par4") = T
    Set BE = zap1.OpenRecordset()
 
    rst.AddNew
    rst.Fields(0).Value = "BBI"
    rst.Fields(1).Value = D1
    rst.Fields(2).Value = BE.[ICCODE].Value
    rst.Fields(3).Value = BE.[ELTCODE].Value
    rst.Fields(9).Value = BE.NN.Value
    rst.Fields(10).Value = BE![NNEL].Value
    'rst.Fields(11).Value = be.[Iso].Value
    rst.Fields(12).Value = BE.[NNIS].Value
    rst.Fields(13).Value = "BOOK BEGINNING"
    rst.Fields(14).Value = BE.[UNI].Value
   
    rst.Update
    BE.CLOSE

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



mobile

Эксперт MS Access

26772 / 14451 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

10.12.2013, 16:44

2

Цитата
Сообщение от zvs
Посмотреть сообщение

Все работает до тех пор пока на параметр-дату( D1)нет записи…ошибка-3021…
Мне нужно при этой ошибке в таблицу rst.Fields(2)…rst.Fields(12) прописать 0 и перейти к следующей процедуре…

Поскольку неясно куда надо переходить и в каком месте кода проверять отсутствие данных, то скажем так:
перед rst.AddNew пишем проверку D1 и если NULL, обходим цикл записи

Visual Basic
1
2
3
4
5
If Len(D1 & "")=0 Then Goto МеткаОбойти
rst.AddNew
...........
rst.Update
МеткаОбойти:



1



zvs

0 / 0 / 0

Регистрация: 04.11.2012

Сообщений: 56

11.12.2013, 12:38

 [ТС]

3

Цитата
Сообщение от mobile
Посмотреть сообщение

Поскольку неясно куда надо переходить и в каком месте кода проверять отсутствие данных, то скажем так:
перед rst.AddNew пишем проверку D1 и если NULL, обходим цикл записи

Visual Basic
1
2
3
4
5
If Len(D1 & "")=0 Then Goto МеткаОбойти
rst.AddNew
...........
rst.Update
МеткаОбойти:

У меня ошибка срабатывает на rst2.MoveFirst, посколко на дату D1(дата из формы) в запросе нет записей и естественно нет первой строки…., для этого случая мне нужно таблицу на дату D1 заполнить поля нулями….(таблица используется для отчета за период)…



0



mobile

Эксперт MS Access

26772 / 14451 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

11.12.2013, 13:04

4

Цитата
Сообщение от zvs
Посмотреть сообщение

У меня ошибка срабатывает на rst2.MoveFirst, посколко на дату D1(дата из формы) в запросе нет записей и естественно нет первой строки…., для этого случая мне нужно таблицу на дату D1 заполнить поля нулями

Может быть так

Visual Basic
1
2
3
4
IF rst2.BOF and rst2.EOF THEN
   'Здесь записать в таблицу нужные данные
End If
    rst2.MoveFirst



0



Модератор

Эксперт MS Access

11267 / 4597 / 740

Регистрация: 07.08.2010

Сообщений: 13,182

Записей в блоге: 4

11.12.2013, 13:16

5

применяю только Do While rst2.EOF = False
хотя из-за вашего неполного кода нельзя понять, что куда читается -пишется
rst
rst2
be



0



zvs

0 / 0 / 0

Регистрация: 04.11.2012

Сообщений: 56

11.12.2013, 15:51

 [ТС]

6

Цитата
Сообщение от mobile
Посмотреть сообщение

Поскольку неясно куда надо переходить и в каком месте кода проверять отсутствие данных, то скажем так:
перед rst.AddNew пишем проверку D1 и если NULL, обходим цикл записи

Visual Basic
1
2
3
4
5
If Len(D1 & "")=0 Then Goto МеткаОбойти
rst.AddNew
...........
rst.Update
МеткаОбойти:

спасибо за подсказку, я ею воспользовалась…но у меня возникла другая проблема -Как правильно прописать повторяющуюся ошибку…Первый раз все правильно работает, а во второй раз не видит метки….

QBasic/QuickBASIC
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
FUNCTION glrepVZ(T, D1, D2 AS Variant)
Set DB = CurrentDb
Set rst = DB.OpenRecordset("tblGLAll", DB_OPEN_DYNASET)
     gl = "qrtGLZA"
    Set zap1 = DB.QueryDefs(gl)
     IF NOT rst.BOF THEN
        rst.MoveFirst
        DO UNTIL rst.EOF
            rst.Delete
            rst.MoveNext
        LOOP
    END IF
    zap1.Parameters("Par1") = D1
    zap1.Parameters("Par2") = "U"
    zap1.Parameters("Par3") = T
 
    Set BE = zap1.OpenRecordset()
 
    rst.AddNew
    rst.Fields(0).Value = "BBI"
    rst.Fields(1).Value = D1
     
     ON ERROR GOTO RR
 IF RR THEN
RR:
 
   rst.Fields(3).Value = "U"
    rst.Fields(9).Value = "0"
    rst.Fields(10).Value = "0"
    rst.Fields(11).Value = "0"
    rst.Fields(12).Value = "0"
   rst.Fields(13).Value = "BOOK BEGINNING"
    rst.Fields(14).Value = "G"
    rst.Update
ELSE
       rst.Fields(3).Value = BE.[ELTCODE].Value
    rst.Fields(9).Value = BE.NN.Value
    rst.Fields(10).Value = BE![NNEL].Value
    rst.Fields(11).Value = BE.[Iso].Value
    rst.Fields(12).Value = BE.[NNIS].Value
    rst.Fields(13).Value = "BOOK BEGINNING"
    rst.Fields(14).Value = BE.[UNI].Value
    rst.Update
    BE.CLOSE
    END IF
    zap1.Parameters("Par1") = D1
    zap1.Parameters("Par2") = "P"
    zap1.Parameters("Par3") = T
    Set BE = zap1.OpenRecordset()
        rst.AddNew
    rst.Fields(0).Value = "BBI"
    rst.Fields(1).Value = D1
    
          ON ERROR GOTO R ‘-(не переходит на метку R)
 IF R THEN
‘ MsgBox "R=" & R
R:
 
   rst.Fields(3).Value = "P"
    rst.Fields(9).Value = "0"
    rst.Fields(10).Value = "0"
    rst.Fields(11).Value = "0"
    rst.Fields(12).Value = "0"
   rst.Fields(13).Value = "BOOK BEGINNING"
    rst.Fields(14).Value = ""
    rst.Update
    ELSE
    rst.Fields(3).Value = BE.[ELTCODE].Value
    rst.Fields(9).Value = BE.NN.Value
    rst.Fields(10).Value = BE![NNEL].Value
    rst.Fields(11).Value = BE.[Iso].Value
    rst.Fields(12).Value = BE.[NNIS].Value
    rst.Fields(13).Value = "BOOK BEGINNING"
    rst.Fields(14).Value = BE.[UNI].Value
    rst.Update
    BE.CLOSE
  END IF



0



  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • [RESOLVED] Run-Time Error ‘3021’ No Current Record Found

  1. Oct 20th, 2014, 12:59 PM


    #1

    vb6coder14 is offline

    Thread Starter


    Hyperactive Member


    Resolved [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

    Code:

    Option Explicit
    
    Public Sub modDeterminePrice()
    
    
        On Error GoTo ErrorRoutine
    
    
        Dim dbCtrlRec As Database
        Dim rsCtrlRec As Recordset
     
    
        Set dbCtrlRec = OpenDatabase(App.Path & "" & "LLSYS.mdb")
        Set rsCtrlRec = dbCtrlRec.OpenRecordset("SYS_CONTROL_RECORD")
        
        MsgBox rsCtrlRec.Fields("mpSalesRankTier1")   '<- Failure occurs here
    
    
    Exit Sub
        
    ErrorRoutine:
    
        If Err.Number > 0 Then
            Call gscErrRtn.gscErrRtn
        End If
    
    End Sub

    Last edited by vb6coder14; Oct 20th, 2014 at 01:03 PM.


  2. Oct 20th, 2014, 01:43 PM


    #2

    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

    Code:

     Option Explicit
    
    Public Sub modDeterminePrice()
    
    
        On Error GoTo ErrorRoutine
    
    
        Dim dbCtrlRec As DAO.Database
        Dim rsCtrlRec As DAO.Recordset
     
    
        Set dbCtrlRec = OpenDatabase(App.Path & "" & "LLSYS.mdb")
        Set rsCtrlRec = dbCtrlRec.OpenRecordset("SYS_CONTROL_RECORD", dbOpenTable)
        
        MsgBox rsCtrlRec.Fields("mpSalesRankTier1")   '<- Failure occurs here
    
    
    Exit Sub
        
    ErrorRoutine:
    
        If Err.Number > 0 Then
            Call gscErrRtn.gscErrRtn
        End If
    
    End Sub

    JG

    … If your problem is fixed don’t forget to mark your threads as resolved using the Thread Tools menu …


  3. Oct 20th, 2014, 02:57 PM


    #3

    vb6coder14 is offline

    Thread Starter


    Hyperactive Member


    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.


  4. Oct 20th, 2014, 03:32 PM


    #4

    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 …»

    Take Care,
    Elroy


  5. Oct 20th, 2014, 03:42 PM


    #5

    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 :

    rsCtrlRec.MoveFirst

    to avoid BOF conditions

    4- Make sure you have records :

    msgbox rsCtrlRec.RecordCount

    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

    msgbox rsCtrlRec.Fields(0)

    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.


  6. Oct 20th, 2014, 04:03 PM


    #6

    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.


  7. Oct 20th, 2014, 04:16 PM


    #7

    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.

    dao360.chm


  8. Oct 20th, 2014, 04:25 PM


    #8

    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

    Dim a$

    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


  9. Oct 20th, 2014, 04:39 PM


    #9

    Re: Run-Time Error ‘3021’ No Current Record Found

    *laughs heartily*

    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.

    Take Care,
    Elroy


  10. Oct 20th, 2014, 04:40 PM


    #10

    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


  11. Oct 20th, 2014, 04:54 PM


    #11

    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.


  12. Oct 20th, 2014, 04:58 PM


    #12

    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.


  13. Oct 20th, 2014, 05:00 PM


    #13

    vb6coder14 is offline

    Thread Starter


    Hyperactive Member


    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?


  14. Oct 20th, 2014, 05:01 PM


    #14

    Re: Run-Time Error ‘3021’ No Current Record Found

    Hey Elroy…

    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


  15. Oct 20th, 2014, 05:03 PM


    #15

    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


  16. Oct 20th, 2014, 05:08 PM


    #16

    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


  17. Oct 20th, 2014, 05:13 PM


    #17

    Re: Run-Time Error ‘3021’ No Current Record Found

    Quote Originally Posted by Elroy
    View Post

    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.

    A recordset, depending on type & sql provider, can have an initial value of -1 if I recall correctly


  18. Oct 20th, 2014, 05:17 PM


    #18

    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


  19. Oct 20th, 2014, 05:24 PM


    #19

    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)


  20. Oct 20th, 2014, 05:28 PM


    #20

    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:

    Code:

    Public Function DoubleVal(fld As DAO.Field, Optional dDefault As Double = 0) As Double
        If IsNull(fld) Then
            DoubleVal = dDefault
        Else
            On Error Resume Next
            DoubleVal = fld
            On Error GoTo 0
        End If
    End Function

    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.


  21. Oct 20th, 2014, 05:35 PM


    #21

    Re: Run-Time Error ‘3021’ No Current Record Found

    Quote Originally Posted by Navion
    View Post

    … 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…

    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

    Code:

    ... assumption is recordset was returned. If EOF is false, should be on 1st record
       Do Until .EOF = True
          ... process
          .MoveNext
       Loop


  22. Oct 20th, 2014, 05:39 PM


    #22

    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.


  23. Oct 20th, 2014, 05:46 PM


    #23

    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.


  24. Oct 20th, 2014, 05:55 PM


    #24

    Re: Run-Time Error ‘3021’ No Current Record Found

    Quote Originally Posted by LaVolpe
    View Post

    A recordset, depending on type & sql provider, can have an initial value of -1 if I recall correctly

    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.


  25. Oct 20th, 2014, 06:40 PM


    #25

    Re: Run-Time Error ‘3021’ No Current Record Found

    When using DAO .RecordCount will give you the result only after a .MoveLast method

    JG

    … If your problem is fixed don’t forget to mark your threads as resolved using the Thread Tools menu …


  26. Oct 20th, 2014, 07:22 PM


    #26

    Re: Run-Time Error ‘3021’ No Current Record Found

    Quote Originally Posted by jggtz
    View Post

    When using DAO .RecordCount will give you the result only after a .MoveLast method

    Hummm good point, you are right about that. But if I remember correctly (I think I do, but maybe not), that does not apply to a recordset after an Index has been set.


  27. Oct 20th, 2014, 08:16 PM


    #27

    Re: Run-Time Error ‘3021’ No Current Record Found

    Actually, it still applies after an index has been set. It’s actually the only major bug in the DAO that I’m aware of. And, the situation is worse than just needing a .MoveLast execution. It still may not work. One thing that is true though is that .RecordCount will always be greater than zero if there are records. Beyond that, it’s just completely untrustworthy. Here are two functions I use instead:

    Code:

    Public Function bHasRecords(rs As Recordset) As Boolean
        ' The RecordCount property is generally bad news.
        ' It doesn't always work right even with a MoveLast.
        ' It does seem to be reliable as a check of the existence of ANY records.
        ' But even here, sometimes it will report -1 as "no records" rather than zero.
        bHasRecords = rs.RecordCount > 0
    End Function
    
    Public Function lExactRecordCount(rs As Recordset) As Long
        ' Be careful with this.  You can NOT be in an "EDIT" or "UPDATE" mode to use this.
        ' However, it will attempt to preserve the active record.
        Dim Bookmark As String
        Dim l As Long
        '
        If (rs.BOF = False) And (rs.EOF = False) Then Bookmark = rs.Bookmark
        '
        ' Count the records.
        If bHasRecords(rs) Then
            rs.MoveFirst
            l = 1
            Do
                rs.MoveNext
                If rs.EOF Then Exit Do
                l = l + 1
            Loop
        End If
        '
        If Len(Bookmark) <> 0 Then rs.Bookmark = Bookmark
        lExactRecordCount = l
    End Function


  28. Oct 20th, 2014, 08:19 PM


    #28

    Re: Run-Time Error ‘3021’ No Current Record Found

    Just as a further comment, the only other «bug» I know of in the DAO is that the default timing settings sometimes cause users to have unwanted collisions in a multi-user environment. If asked, I’ll post a fix that I’ve used for years and is working flawlessly in many installations.

    In fact, after staring at some code, I’ll outline the problem. The Jet Engine has «read ahead» and «cached write» options. In a multi-user environment, both of these can cause problems. Here, I’ll go ahead and post it. The following turns the «read ahead» and the «cached write» options off so that all reads and writes to/from an MDB file are truly coming off the server disk.

    Code:

        DBEngine.SetOption dbExclusiveAsyncDelay, 2000
        DBEngine.SetOption dbSharedAsyncDelay, 0
        DBEngine.SetOption dbFlushTransactionTimeout, 500
        '
        DBEngine.SetOption dbUserCommitSync, "yes"
        DBEngine.SetOption dbImplicitCommitSync, "yes"
        DBEngine.SetOption dbLockRetry, 20
        DBEngine.SetOption dbPageTimeout, 5000
        DBEngine.SetOption dbMaxLocksPerFile, 9500
        DBEngine.SetOption dbLockDelay, 100
        DBEngine.SetOption dbRecycleLVs, 0

    I’ve got about five pages of comments also in the procedure that calls this. If anyone wants it, let me know.

    Last edited by Elroy; Oct 20th, 2014 at 08:24 PM.


  29. Oct 20th, 2014, 08:21 PM


    #29

    Re: Run-Time Error ‘3021’ No Current Record Found

    I had an issue once using DAO in VB5 on an Access DB where the .MoveLast triggered an error message something like «Statement to complex to process»

    It took a bit to find the root of the problem, surely a simple move last can not be to complicated and the query was rather basic.

    Turned out to be a null value in a QTY field where who ever created the DB decided that QTY should be a text field and allow null values.

    Still not sure why it threw that error message but placing a value of 0 in the null fields corrected the problem then I added a default value of «0» to prevent the problem from happening again.


  30. Oct 20th, 2014, 08:23 PM


    #30

    vb6coder14 is offline

    Thread Starter


    Hyperactive Member


    Re: Run-Time Error ‘3021’ No Current Record Found

    This has been a great discussion and I’ve certainly picked up several valuable tips from reading all of the responses. Thank you all very much for your input. I’m marking this thread resolved now.


  31. Oct 20th, 2014, 11:24 PM


    #31

    Re: Run-Time Error ‘3021’ No Current Record Found

    Quote Originally Posted by Elroy
    View Post

    Actually, it still applies after an index has been set. It’s actually the only major bug in the DAO that I’m aware of. And, the situation is worse than just needing a .MoveLast execution. It still may not work. One thing that is true though is that .RecordCount will always be greater than zero if there are records. Beyond that, it’s just completely untrustworthy. Here are two functions I use instead:

    Again, only out of memories… I am pretty sure I have come across the problem before, and the DAO has a method to force its own reading of the whole dataset in order to return the proper RecordCount. Again not sure, but I will be browsing through some old code to see if i find it. Then as i finish writing these few words, certainty rises a notch of two because I remember testing the feature with very large number of records in a table. Will see.


  32. Oct 21st, 2014, 12:17 AM


    #32

    Re: [RESOLVED] Run-Time Error ‘3021’ No Current Record Found

    I remember working with some large tables in VB5 and using the .MoveLast and .Recordcount to set the max value of a progress bar before looping through the data. I do not recall having saw any issues there but it was long ago.


  33. Oct 21st, 2014, 08:01 AM


    #33

    Re: [RESOLVED] Run-Time Error ‘3021’ No Current Record Found

    I can absolutely promise that .MoveLast doesn’t always work to fix the .RecordCount problem. In my mind, I always thought it was an indexing thing. Say, you may have a PrimaryKey index on «Name». And then «AAAbernathy» is added first, and then «ZZZombie» added second, with 1000s of records subsequently added in between. In that case (through whatever btree or indexing method it internally uses), it comes nowhere close to actually «touching» and counting all the records to do a .MoveLast.

    But that’s all high supposition on my part. I just know .RecordCount isn’t accurate unless you «touch» every record in the database.

    And, long ago, I decided that, if I’m going to «touch» every record in the database, I’ll just count them myself.


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • [RESOLVED] Run-Time Error ‘3021’ No Current Record Found


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Правила форума
Темы, в которых будет сначала написано «что нужно сделать», а затем просьба «помогите», будут закрыты.
Читайте требования к создаваемым темам.

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
Повелитель 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
Повелитель 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

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 0

Are you trying to use Microsoft Access, but are you getting the error ‘3021’?

Tech Support 24/7

Ask a Tech Specialist Online

Connect with the Expert via email, text or phone. Include photos, documents, and more. Get step-by-step instructions from verified Tech Support Specialists.

Ask a Tech Specialist Online

On this page, you will find more information about the most common causes and most relevant solutions for the Microsoft Access error ‘3021’. Do you need help straight away? Visit our support page.

Error information

How to solve Microsoft Access error 3021

We’ve created a list of solutions which you can follow if you want to solve this Microsoft Access problem yourself. Do you need more help? Visit our support page if you need professional support with Microsoft Access right away.

Tech Support 24/7

Ask a Tech Specialist Online

Connect with the Expert via email, text or phone. Include photos, documents, and more. Get step-by-step instructions from verified Tech Support Specialists.

Ask a Tech Specialist Online

Have you found a solution yourself, but it is not in the list? Share your solution in the comments below.

Need more help?

Do you need more help?

Tech experts are ready to answer your questions.

Ask a question

Понравилась статья? Поделить с друзьями:

Читайте также:

  • Accu chek e 1 код ошибки
  • Accu chek active ошибка еее что делать
  • Access номер ошибки 2102
  • Accu chek active ошибка eee как устранить
  • Accu chek active ошибка e 5 что значит

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии