Runtime error 3021 как исправить

Ошибка 3021 Ошибка Microsoft Access 3021 ошибки могут привести к зависанию или сбою компьютера, а также к возможному заражению вредоносным ПО. Выполните следующие простые действия, чтобы исправить Runtime Errors ошибки быстро и просто.

В этой статье представлена ошибка с номером Ошибка 3021, известная как Ошибка Microsoft Access 3021, описанная как Текущих записей нет.

О программе 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

Ошибки времени выполнения происходят без предупреждения. Сообщение об ошибке может появиться на экране при любом запуске %программы%. Фактически, сообщение об ошибке или другое диалоговое окно может появляться снова и снова, если не принять меры на ранней стадии.

Возможны случаи удаления файлов или появления новых файлов. Хотя этот симптом в основном связан с заражением вирусом, его можно отнести к симптомам ошибки времени выполнения, поскольку заражение вирусом является одной из причин ошибки времени выполнения. Пользователь также может столкнуться с внезапным падением скорости интернет-соединения, но, опять же, это не всегда так.

Fix Ошибка Microsoft Access 3021 (Error Ошибка 3021)
(Только для примера)

Причины Ошибка Microsoft Access 3021 — Ошибка 3021

При разработке программного обеспечения программисты составляют код, предвидя возникновение ошибок. Однако идеальных проектов не бывает, поскольку ошибки можно ожидать даже при самом лучшем дизайне программы. Глюки могут произойти во время выполнения программы, если определенная ошибка не была обнаружена и устранена во время проектирования и тестирования.

Ошибки во время выполнения обычно вызваны несовместимостью программ, запущенных в одно и то же время. Они также могут возникать из-за проблем с памятью, плохого графического драйвера или заражения вирусом. Каким бы ни был случай, проблему необходимо решить немедленно, чтобы избежать дальнейших проблем. Ниже приведены способы устранения ошибки.

Методы исправления

Ошибки времени выполнения могут быть раздражающими и постоянными, но это не совсем безнадежно, существует возможность ремонта. Вот способы сделать это.

Если метод ремонта вам подошел, пожалуйста, нажмите кнопку upvote слева от ответа, это позволит другим пользователям узнать, какой метод ремонта на данный момент работает лучше всего.

Обратите внимание: ни ErrorVault.com, ни его авторы не несут ответственности за результаты действий, предпринятых при использовании любого из методов ремонта, перечисленных на этой странице — вы выполняете эти шаги на свой страх и риск.

Метод 1 — Закройте конфликтующие программы

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

  • Откройте диспетчер задач, одновременно нажав Ctrl-Alt-Del. Это позволит вам увидеть список запущенных в данный момент программ.
  • Перейдите на вкладку «Процессы» и остановите программы одну за другой, выделив каждую программу и нажав кнопку «Завершить процесс».
  • Вам нужно будет следить за тем, будет ли сообщение об ошибке появляться каждый раз при остановке процесса.
  • Как только вы определите, какая программа вызывает ошибку, вы можете перейти к следующему этапу устранения неполадок, переустановив приложение.

Метод 2 — Обновите / переустановите конфликтующие программы

Использование панели управления

  • В Windows 7 нажмите кнопку «Пуск», затем нажмите «Панель управления», затем «Удалить программу».
  • В Windows 8 нажмите кнопку «Пуск», затем прокрутите вниз и нажмите «Дополнительные настройки», затем нажмите «Панель управления»> «Удалить программу».
  • Для Windows 10 просто введите «Панель управления» в поле поиска и щелкните результат, затем нажмите «Удалить программу».
  • В разделе «Программы и компоненты» щелкните проблемную программу и нажмите «Обновить» или «Удалить».
  • Если вы выбрали обновление, вам просто нужно будет следовать подсказке, чтобы завершить процесс, однако, если вы выбрали «Удалить», вы будете следовать подсказке, чтобы удалить, а затем повторно загрузить или использовать установочный диск приложения для переустановки. программа.

Использование других методов

  • В Windows 7 список всех установленных программ можно найти, нажав кнопку «Пуск» и наведя указатель мыши на список, отображаемый на вкладке. Вы можете увидеть в этом списке утилиту для удаления программы. Вы можете продолжить и удалить с помощью утилит, доступных на этой вкладке.
  • В Windows 10 вы можете нажать «Пуск», затем «Настройка», а затем — «Приложения».
  • Прокрутите вниз, чтобы увидеть список приложений и функций, установленных на вашем компьютере.
  • Щелкните программу, которая вызывает ошибку времени выполнения, затем вы можете удалить ее или щелкнуть Дополнительные параметры, чтобы сбросить приложение.

Метод 3 — Обновите программу защиты от вирусов или загрузите и установите последнюю версию Центра обновления Windows.

Заражение вирусом, вызывающее ошибку выполнения на вашем компьютере, необходимо немедленно предотвратить, поместить в карантин или удалить. Убедитесь, что вы обновили свою антивирусную программу и выполнили тщательное сканирование компьютера или запустите Центр обновления Windows, чтобы получить последние определения вирусов и исправить их.

Метод 4 — Переустановите библиотеки времени выполнения

Вы можете получить сообщение об ошибке из-за обновления, такого как пакет MS Visual C ++, который может быть установлен неправильно или полностью. Что вы можете сделать, так это удалить текущий пакет и установить новую копию.

  • Удалите пакет, выбрав «Программы и компоненты», найдите и выделите распространяемый пакет Microsoft Visual C ++.
  • Нажмите «Удалить» в верхней части списка и, когда это будет сделано, перезагрузите компьютер.
  • Загрузите последний распространяемый пакет от Microsoft и установите его.

Метод 5 — Запустить очистку диска

Вы также можете столкнуться с ошибкой выполнения из-за очень нехватки свободного места на вашем компьютере.

  • Вам следует подумать о резервном копировании файлов и освобождении места на жестком диске.
  • Вы также можете очистить кеш и перезагрузить компьютер.
  • Вы также можете запустить очистку диска, открыть окно проводника и щелкнуть правой кнопкой мыши по основному каталогу (обычно это C :)
  • Щелкните «Свойства», а затем — «Очистка диска».

Метод 6 — Переустановите графический драйвер

Если ошибка связана с плохим графическим драйвером, вы можете сделать следующее:

  • Откройте диспетчер устройств и найдите драйвер видеокарты.
  • Щелкните правой кнопкой мыши драйвер видеокарты, затем нажмите «Удалить», затем перезагрузите компьютер.

Метод 7 — Ошибка выполнения, связанная с IE

Если полученная ошибка связана с Internet Explorer, вы можете сделать следующее:

  1. Сбросьте настройки браузера.
    • В Windows 7 вы можете нажать «Пуск», перейти в «Панель управления» и нажать «Свойства обозревателя» слева. Затем вы можете перейти на вкладку «Дополнительно» и нажать кнопку «Сброс».
    • Для Windows 8 и 10 вы можете нажать «Поиск» и ввести «Свойства обозревателя», затем перейти на вкладку «Дополнительно» и нажать «Сброс».
  2. Отключить отладку скриптов и уведомления об ошибках.
    • В том же окне «Свойства обозревателя» можно перейти на вкладку «Дополнительно» и найти пункт «Отключить отладку сценария».
    • Установите флажок в переключателе.
    • Одновременно снимите флажок «Отображать уведомление о каждой ошибке сценария», затем нажмите «Применить» и «ОК», затем перезагрузите компьютер.

Если эти быстрые исправления не работают, вы всегда можете сделать резервную копию файлов и запустить восстановление на вашем компьютере. Однако вы можете сделать это позже, когда перечисленные здесь решения не сработают.

Другие языки:

How to fix Error 3021 (Microsoft Access Error 3021) — No current record.
Wie beheben Fehler 3021 (Microsoft Access-Fehler 3021) — Kein aktueller Rekord.
Come fissare Errore 3021 (Errore di Microsoft Access 3021) — Nessun record attuale.
Hoe maak je Fout 3021 (Microsoft Access-fout 3021) — Geen actueel record.
Comment réparer Erreur 3021 (Erreur d’accès Microsoft 3021) — Aucun enregistrement actuel.
어떻게 고치는 지 오류 3021 (마이크로소프트 액세스 오류 3021) — 현재 기록이 없습니다.
Como corrigir o Erro 3021 (Erro 3021 do Microsoft Access) — Nenhum registro atual.
Hur man åtgärdar Fel 3021 (Microsoft Access Error 3021) — Inget aktuellt rekord.
Jak naprawić Błąd 3021 (Błąd Microsoft Access 3021) — Brak aktualnego rekordu.
Cómo arreglar Error 3021 (Error de Microsoft Access 3021) — Sin registro actual.

The Author Об авторе: Фил Харт является участником сообщества Microsoft с 2010 года. С текущим количеством баллов более 100 000 он внес более 3000 ответов на форумах Microsoft Support и создал почти 200 новых справочных статей в Technet Wiki.

Следуйте за нами: Facebook Youtube Twitter

Последнее обновление:

13/03/22 03:56 : Пользователь Windows 8.1 проголосовал за то, что метод восстановления 1 работает для него.

Рекомендуемый инструмент для ремонта:

Этот инструмент восстановления может устранить такие распространенные проблемы компьютера, как синие экраны, сбои и замораживание, отсутствующие DLL-файлы, а также устранить повреждения от вредоносных программ/вирусов и многое другое путем замены поврежденных и отсутствующих системных файлов.

ШАГ 1:

Нажмите здесь, чтобы скачать и установите средство восстановления Windows.

ШАГ 2:

Нажмите на Start Scan и позвольте ему проанализировать ваше устройство.

ШАГ 3:

Нажмите на Repair All, чтобы устранить все обнаруженные проблемы.

СКАЧАТЬ СЕЙЧАС

Совместимость

Требования

1 Ghz CPU, 512 MB RAM, 40 GB HDD
Эта загрузка предлагает неограниченное бесплатное сканирование ПК с Windows. Полное восстановление системы начинается от $19,95.

ID статьи: ACX06411RU

Применяется к: Windows 10, Windows 8.1, Windows 7, Windows Vista, Windows XP, Windows 2000

Icon Ex Номер ошибки: Ошибка 3021
Название ошибки: Excel Error 3021
Описание ошибки: Ошибка 3021: Возникла ошибка в приложении Microsoft Excel. Приложение будет закрыто. Приносим извинения за неудобства.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Excel
Относится к: Windows XP, Vista, 7, 8, 10, 11

Сводка «Excel Error 3021

Это наиболее распространенное условие «Excel Error 3021», известное как ошибка времени выполнения (ошибка). Разработчики, такие как Microsoft Corporation, обычно проходят через несколько контрольных точек перед запуском программного обеспечения, такого как Microsoft Excel. Хотя эти превентивные действия принимаются, иногда ошибки, такие как ошибка 3021, будут пропущены.

Ошибка 3021 также отображается как «Excel Error 3021». Это распространенная ошибка, которая может возникнуть после установки программного обеспечения. После того, как об ошибке будет сообщено, Microsoft Corporation отреагирует и быстро исследует ошибки 3021 проблемы. Затем они исправляют дефектные области кода и сделают обновление доступным для загрузки. Если есть запрос на обновление Microsoft Excel, это обычно обходной путь для устранения проблем, таких как ошибка 3021 и другие ошибки.

Как триггеры Runtime Error 3021 и что это такое?

Вполне вероятно, что при загрузке Microsoft Excel вы столкнетесь с «Excel Error 3021». Причины сбоев обработки можно отличить, классифицируя ошибки 3021 следующим образом:.

Ошибка 3021 Crash — Ошибка 3021 является хорошо известной, которая происходит, когда неправильная строка кода компилируется в исходный код программы. Это возникает, когда Microsoft Excel не работает должным образом или не знает, какой вывод будет подходящим.

Утечка памяти «Excel Error 3021» — при утечке памяти Microsoft Excel это может привести к медленной работе устройства из-за нехватки системных ресурсов. Возможные искры включают сбой освобождения, который произошел в программе, отличной от C ++, когда поврежденный код сборки неправильно выполняет бесконечный цикл.

Ошибка 3021 Logic Error — логическая ошибка возникает, когда компьютер производит неправильный вывод, даже если вход правильный. Это может произойти, когда исходный код Microsoft Corporation имеет уязвимость в отношении передачи данных.

В большинстве случаев проблемы с файлами Excel Error 3021 связаны с отсутствием или повреждением файла связанного Microsoft Excel вредоносным ПО или вирусом. Большую часть проблем, связанных с данными файлами, можно решить посредством скачивания и установки последней версии файла Microsoft Corporation. В качестве последней меры мы рекомендуем использовать очиститель реестра для исправления всех недопустимых Excel Error 3021, расширений файлов Microsoft Corporation и других ссылок на пути к файлам, по причине которых может возникать сообщение об ошибке.

Ошибки Excel Error 3021

Общие проблемы Excel Error 3021, возникающие с Microsoft Excel:

  • «Ошибка программы Excel Error 3021. «
  • «Ошибка программного обеспечения Win32: Excel Error 3021»
  • «Извините за неудобства — Excel Error 3021 имеет проблему. «
  • «Файл Excel Error 3021 не найден.»
  • «Excel Error 3021 не может быть найден. «
  • «Проблема при запуске приложения: Excel Error 3021. «
  • «Excel Error 3021 не выполняется. «
  • «Ошибка Excel Error 3021. «
  • «Неверный путь к программе: Excel Error 3021. «

Эти сообщения об ошибках Microsoft Corporation могут появляться во время установки программы, в то время как программа, связанная с Excel Error 3021 (например, Microsoft Excel) работает, во время запуска или завершения работы Windows, или даже во время установки операционной системы Windows. При появлении ошибки Excel Error 3021 запишите вхождения для устранения неполадок Microsoft Excel и чтобы HelpMicrosoft Corporation найти причину.

Источник ошибок Excel Error 3021

Проблемы Excel Error 3021 могут быть отнесены к поврежденным или отсутствующим файлам, содержащим ошибки записям реестра, связанным с Excel Error 3021, или к вирусам / вредоносному ПО.

В частности, проблемы с Excel Error 3021, вызванные:

  • Поврежденные ключи реестра Windows, связанные с Excel Error 3021 / Microsoft Excel.
  • Файл Excel Error 3021 поврежден от вирусной инфекции.
  • Другая программа (не связанная с Microsoft Excel) удалила Excel Error 3021 злонамеренно или по ошибке.
  • Другая программа, конфликтующая с Excel Error 3021 или другой общей ссылкой Microsoft Excel.
  • Microsoft Excel/Excel Error 3021 поврежден от неполной загрузки или установки.

Продукт Solvusoft

Загрузка
WinThruster 2022 — Проверьте свой компьютер на наличие ошибок.

Совместима с Windows 2000, XP, Vista, 7, 8, 10 и 11

Установить необязательные продукты — WinThruster (Solvusoft) | Лицензия | Политика защиты личных сведений | Условия | Удаление

hawk1

2 / 2 / 0

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

Сообщений: 213

1

01.04.2016, 13:57. Показов 2809. Ответов 3

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


Есть следующий код

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Private Sub ÎáùååÊîëè÷åñòâî_AfterUpdate()
   Dim qryGiven, qryReturned As QueryDef
   Dim rsGiven, rsReturned As DAO.Recordset
   Dim iGiven, iReturned As Byte
   
   If Me.NewRecord Then
      Me.ÂÍàëè÷èè.Value = Me.ÎáùååÊîëè÷åñòâî.Value
   Else
      Set qryGiven = CurrentDb.QueryDefs("Âûäàíî îáðàçöîâ")
      qryGiven.Parameters("ïÎáðàçåö").Value = CByte(Me.Êîä)
      Set rsGiven = qryGiven.OpenRecordset
      iGiven = rsGiven.Fields("Sum-Êîëè÷åñòâî").Value
      
      Set qryReturned = CurrentDb.QueryDefs("Âîçâðàùåíî îáðàçöîâ")
      qryReturned.Parameters("ïÎáðàçåö").Value = CByte(Me.Êîä)
      Set rsReturned = qryReturned.OpenRecordset
      iReturned = rsReturned.Fields("Sum-Êîëè÷åñòâî").Value
      
      Me.ÂÍàëè÷èè.Value = Me.ÎáùååÊîëè÷åñòâî.Value - iGiven + iReturned
   End If
End Sub

При попытке обратиться к полю запроса выскакивает ошибка Run-time error 3021 Текущая запись не найдена. В чем дело?

Вложения

Тип файла: rar Фото дети.rar (227.0 Кб, 4 просмотров)

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



0



Programming

Эксперт

94731 / 64177 / 26122

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

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

01.04.2016, 13:57

3

mobile

Эксперт MS Access

26772 / 14451 / 3192

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

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

01.04.2016, 14:18

2

Рекордсет пустой, потому ошибка. Попробуйте так

Visual Basic
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
Private Sub Form_AfterUpdate()
   Dim qryGiven, qryReturned As QueryDef
   Dim rsGiven, rsReturned As DAO.Recordset
   Dim iGiven, iReturned As Byte
   
   If Me.NewRecord Then
      Me.ВНаличии.Value = Me.ОбщееКоличество.Value
   Else
      Set qryGiven = CurrentDb.QueryDefs("Выдано образцов")
      qryGiven.Parameters("пОбразец").Value = Me.Код.Value
      Set rsGiven = qryGiven.OpenRecordset
      If Not rsGiven.EOF Then  'Проверяем рекордсет rsGiven на "пустоту"
        iGiven = rsGiven.Fields("[Sum-Количество]").Value
      Else
        iGiven = 0
      End If
      
      Set qryReturned = CurrentDb.QueryDefs("Возвращено образцов")
      qryReturned.Parameters("пОбразец").Value = Me.Код.Value
      Set rsReturned = qryReturned.OpenRecordset
      If Not rsReturned.EOF Then  'Проверяем rsReturned рекордсет на "пустоту"
        iReturned = rsReturned.Fields("[Sum-Количество]").Value
      Else
        iReturned = 0
      End If
      
      Me.ВНаличии.Value = Me.ОбщееКоличество.Value - iGiven + iReturned
   End If
End Sub



1



2 / 2 / 0

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

Сообщений: 213

01.04.2016, 16:30

 [ТС]

3

Теперь вылетает ошибка 2115 Макрос или функция,связанные со свойством «До обновления» или «Условие на значение» этого поля, не позволяет приложению Microsoft Access сохранить данные в этом поле, хотя там ничего не задано



0



шапоклякистка 8-го дня

3672 / 2232 / 391

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

Сообщений: 4,647

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

01.04.2016, 19:38

4

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

связанные со свойством «До обновления»

Ну и ищите причину в функции «до обновленя». Эта-то фунция после обновления:

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

Private Sub Form_AfterUpdate()



1



  • 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

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

Сейчас этот форум просматривают: SemrushBot и гости: 1

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

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

  • Runtime error 30009
  • Runtime error 8020 error reading comm device
  • Runtime error 3 trap вторая мировая
  • Runtime error 28 out of stack space
  • Runtime error 339 mswinsck ocx

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

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