Ошибочный аргумент 3001

Как исправить время выполнения Ошибка 3001 Ошибка Microsoft Access 3001 В этой статье представлена ошибка с номером Ошибка 3001, известная как Ошибка Microsoft Access 3001, описанная как Недействительным аргумент. Информация об ошибке Имя ошибки: Ошибка Microsoft Access 3001 Номер ошибки: Ошибка 3001 Описание: Недействительным аргумент. Программное обеспечение: Microsoft Access Разработчик: Microsoft Этот инструмент исправления […]

Содержание

  1. Как исправить время выполнения Ошибка 3001 Ошибка Microsoft Access 3001
  2. Runtime error 3001 ‘Arguments are of the wrong type or out of acceptable range. ‘
  3. 2 Answers 2
  4. Thread: [RESOLVED] Run-time error 3001 on recordset.find
  5. [RESOLVED] Run-time error 3001 on recordset.find
  6. Run time error 3001
  7. Answered by:
  8. Question
  9. Answers
  10. All replies

Как исправить время выполнения Ошибка 3001 Ошибка Microsoft Access 3001

В этой статье представлена ошибка с номером Ошибка 3001, известная как Ошибка Microsoft Access 3001, описанная как Недействительным аргумент.

Информация об ошибке

Имя ошибки: Ошибка Microsoft Access 3001
Номер ошибки: Ошибка 3001
Описание: Недействительным аргумент.
Программное обеспечение: Microsoft Access
Разработчик: Microsoft

Этот инструмент исправления может устранить такие распространенные компьютерные ошибки, как BSODs, зависание системы и сбои. Он может заменить отсутствующие файлы операционной системы и библиотеки DLL, удалить вредоносное ПО и устранить вызванные им повреждения, а также оптимизировать ваш компьютер для максимальной производительности.

О программе Runtime Ошибка 3001

Время выполнения Ошибка 3001 происходит, когда Microsoft Access дает сбой или падает во время запуска, отсюда и название. Это не обязательно означает, что код был каким-то образом поврежден, просто он не сработал во время выполнения. Такая ошибка появляется на экране в виде раздражающего уведомления, если ее не устранить. Вот симптомы, причины и способы устранения проблемы.

Определения (Бета)

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

  • Access — НЕ ИСПОЛЬЗУЙТЕ этот тег для Microsoft Access, используйте вместо него [ms-access]
  • Аргумент — аргумент значение, передаваемое функции, процедуре или программе командной строки.
  • Access — Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft, которая обычно объединяет реляционное ядро ​​СУБД Microsoft JetACE с графическим пользовательским интерфейсом и инструментами для разработки программного обеспечения.
  • Доступ к Microsoft — Microsoft Access, также известный как Microsoft Office Access, представляет собой систему управления базами данных от Microsoft, которая обычно объединяет реляционное ядро ​​СУБД Microsoft JetACE с графическим пользовательским интерфейсом и инструментами разработки программного обеспечения.
Симптомы Ошибка 3001 — Ошибка Microsoft Access 3001

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

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

(Ошибка Microsoft Access 3001) Repair Tool»/>
(Только для примера)

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

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

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

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

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

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

Источник

Runtime error 3001 ‘Arguments are of the wrong type or out of acceptable range. ‘

I have an Excel table and want to update SQL Server table records’ date value (with getdate function) which referred by 12th column of Excel.

My code is as below, but I’m seeing:

Run-time error 3001 Arguments are of the wrong type or out of acceptable range or are in conflict with one another.

In SQL table MODIFIEDDATE field is datetime type, and MAINREF field is integer type.

I’ve tried to change the SQL query like, (CInt(cell.value))

but, it didn’t work.

2 Answers 2

The ADODB.Recordset object should not be used for an UPDATE query. Execute the SQL statement directly from the ADODB.Connection

There are a couple of ways you can fulfil your requirements and it seems that you are mixing the two.

One way is to update records one at a time, and to do this you would use the Connection object or, more preferably, the Command object. I say preferably because parameterised commands are a far more robust way of executing your SQL. If you intend to use SQL then it’s something you probably ought to read about. The way you would do that is as follows:

The other way is to use Transactions and you would indeed use a Recordset for that (ie similar to what you have already done). In this case I’d suggest it is the better way to do it because executing one command at a time (as in the above code) is very slow. A vastly quicker way would be to commit all your updates in one transaction. Like a parameterised command, it’s also safe from rogue strings entering your SQL command text. The code would look like this:

Источник

Thread: [RESOLVED] Run-time error 3001 on recordset.find

Thread Tools
Display

[RESOLVED] Run-time error 3001 on recordset.find

First post!! Quick bit of info — Have been coding in Vb6 for . well forever! And VBA also. I create VB6 apps, utilising Access mainly, just because thats what the company i work for provide, (office 2003, of course!) but have done some VB.NET apps at home just to get used to the updated syntax. Enough about me! —

Am having a problem with a recordset.find method.

I have a VB6 app that lets people go in to check clients details, but users need a find ability so they dont have to trawl through the entire list.

I have created a button that brings up an InputBox, and the following code works for if a user wants to search a client based on their client ID —

So this code works fine for allowing a user to search for a client based on an ID. And will highlight the row in the datagrid (true DBGrid by the way, not the usual DataGrid) of that selected clients ID.

wont work for allowing a user to search for a client based on their name. I also would like to add in a LIKE filter so if they typed in «Smith» it would go to the first record where Smith is the last name (or first name!).

The error i recieve is error «3001 — Arguments are of the Wrong Type or out of acceptable range or are in conflict with one another»

Im assuming its a Syntax error, but i dont understand why the .find will allow searches on the ID’s of clients, and not their name!?

Источник

Run time error 3001

This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.

Answered by:

Question

I do a Call from a procedure a Sub. Getting an error message “Runtime Error 3001 invalid argument” Pointing to this specific rows:

‘Import the data from sPath with the specification

DoCmd.TransferText acImportDelim, «AA1», «3PGodsmottagning», _

«C:3Pimp» & sPath, True

‘ AA1 is the Text Import Specification ‘3PGodsmottagning is the table

In my own debugging I tried to change the name of the Text Import Specification to a non-existing one “TEST” Then I got another error message, and a understandable one J Runtime Error “3625” – the Textfile specification doesn’t exist. And I’m fine with that. It was just a test.

I have used the Microsoft Methods to create the Specification:

I have also tried to skip the Specification name as its Optional

Variant

A string expression that’s the name of an import or export specification you’ve created and saved in the current database. For a fixed-width text file, you must either specify an argument or use a schema.ini file, which must be stored in the same folder as the imported, linked, or exported text file. To create a schema file, you can use the text import/export wizard to create the file. For delimited text files and Microsoft Word mail merge data files, you can leave this argument blank to select the default import/export specifications.

‘Import the data from sPath with the specification

DoCmd.TransferText acImportDelim, «», «3PGodsmottagning», _

«C:3Pimp» & sPath, True

Running this gave me another Error message “Runtime Error 3270” property not found.

Obviously something or me is wrong. But what?

Best Peter Forss

Answers

I made a new Import Specification. This time I did it without saying «first line contains fieldnames»!!

‘Import the data from sPath with the specification
DoCmd.TransferText acImportDelim, «Godsmottagning_108», «3P Godsmottagning», _
«C:3Pimp» & sPath, True

The HasFieldNames = «True» in the code line above does that part.

Now it runs exactly as I like it to.
Thanks Henry for supporting me.

The new code is:

Sub DailyImport3P()
Dim rs As Recordset
Dim sql As String
Dim db As Database
Set db = CurrentDb()

Dim sPath As String
sPath = Dir$(«C:3Pimp» & «*.txt», vbNormal)
Debug.Print sPath
Do Until sPath = «»
sql = «SELECT * From 3PimporteradefilerGodsmottagning Where FileName=’» & sPath & «‘»
Set rs = CurrentDb.OpenRecordset(sql)

‘Check if the file name existing or not
If rs.RecordCount = 0 Then

‘Import the data from sPath with the specification
DoCmd.TransferText acImportDelim, «Godsmottagning_108», «3P Godsmottagning», _
«C:3Pimp» & sPath, True
Debug.Print sPath

‘Insert Filename not table
sql = «Insert Into 3PimporteradefilerGodsmottagning (FileName) Values(‘» & sPath & «‘)»
CurrentDb.Execute sql
rs.Close
Set rs = Nothing
Set db = Nothing
End If
sPath = Dir$
Loop

Best Peter Forss

What is sPath. Maybe it’s easier to debug if you don’t create the path inline but with a seperate statement, for example:

In the Immediate Window in VBA you will then see what the created Path is.

In your statement you didn’t give the Specification name. I used «AA1» here. If you want to skip it you can’t give «», just let it away like .. acImportDelim,, «3PGoodsmottagning», . If you set to «» then an empty string is passed to the function and the detection with isMissing will fail as it’s not missing, but empty.

In addition: If you have an ImportSpec you don’t have to give the parameter for HasFieldNames. This is part of the Import Specification. But if wamt to skip the SpecificationName add it.

Dim sPath As String
sPath = Dir$(«C:3Pimp» & «*.txt», vbNormal)

Sub DailyImport3P()
Dim rs As Recordset
Dim sql As String

Dim sPath As String
sPath = Dir$(«C:3Pimp» & «*.txt», vbNormal)

Do Until sPath = «»
sql = «SELECT * From 3PimporteradefilerGodsmottagning Where FileName=’» & sPath & «‘»
Set rs = CurrentDb.OpenRecordset(sql)

‘Check if the file name existing or not
If rs.RecordCount = 0 Then

‘Import the data from sPath with the specification
DoCmd.TransferText acImportDelim, «AA1», «3PGodsmottagning», _
«C:3Pimp» & sPath, True

‘Insert Filename not table
sql = «Insert Into 3PimporteradefilerGodsmottagning (FileName) Values(‘» & sPath & «‘)»
CurrentDb.Execute sql
Set rs = Nothing
End If
sPath = Dir$
Loop

Best Peter Forss

Ok, I see. sPAth will not be the problem.

Maybe this will help: Instead of using CurrentDb you should use an explicit db variable

This way you ensure the recordset and the execute are running against the same database instance. You may even loose the recordset if you use CurrentDB in the same loop in the meantime resulting in the error you have seen. CurrentDB may go out of scope and so then does your recordset. See following article in Utter Access Currentdb Vs Dim Db As Dao.database, Any Version

Set rs = Nothing is not enough. Use:

I changed my code into this: (still getting Error message 3001)

Sub DailyImport3P()
Dim rs As Recordset
Dim sql As String
Dim db As Database
Set db = CurrentDb()

Dim sPath As String
sPath = Dir$(«C:3Pimp» & «*.txt», vbNormal)

Do Until sPath = «»
sql = «SELECT * From 3PimporteradefilerGodsmottagning Where FileName=’» & sPath & «‘»
Set rs = db.OpenRecordset(sql)

‘Check if the file name existing or not
If rs.RecordCount = 0 Then

‘Import the data from sPath with the specification
DoCmd.TransferText acImportDelim, «AA1», «3PGodsmottagning», _
«C:3Pimp» & sPath, True

‘Insert Filename not table
sql = «Insert Into 3PimporteradefilerGodsmottagning (FileName) Values(‘» & sPath & «‘)»
db.Execute sql
rs.Close
Set rs = Nothing
Set db = Nothing
End If
sPath = Dir$
Loop

Best Peter Forss

So now you should kick in the debugger. Set a debug stop at the beginning of the procedure and go thru it step by step. Then you can tell us in which line the error occurs and what the parameters are you are using there.

If it’s the DoCmd.TransferText statement you may copy/paste it to the Immediate Window and run it from there where you may get additional information about the error.

As already mentioned: let the parameter HasFieldNames away if you are using an Import Secification and use a variable containing the sImportPath. Some methods of the Comand interpreter object (DoCmd) may not accept inline parameter evaluations.

The debugger stops at the Do.Cmd.TransferText statement. Error 3001. The rest works fine.

I have tried to modify it, starting with:

DoCmd.TransferText acImportDelim, «AA1», «3PGodsmottagning», «C:3Pimp» & sPath, True

2. Removing the param HasFieldNames

DoCmd.TransferText acImportDelim, «AA1», «3PGodsmottagning», «C:3Pimp» & sPath,
Error 3001

3. Removing the «C:3Pimp»

DoCmd.TransferText acImportDelim, «AA1», «3PGodsmottagning», sPath

4 Creating a new Import Spec «AAA3»

DoCmd.TransferText acImportDelim, «AAA3», «3PGodsmottagning», sPath

Best Peter Forss

So, the only reason I can see is that one of the parameters is wrong.

— You obviously checked you have a Specification of this name. Is the specification correct? Is the HeaderLine checked and the fields correctly foirmatted?

— Did you write the table name correctly?

— can you give the content of sPath? Does the file exist?

— Did you check if the file content is correct and containing a header line

— Did you try to run the DoCmd command in the VBA Immediate Window?

— Can you import the file using the data import wizard?

Starting with your first and last line. We (you!) are into something here.

I can Import data, but got some access data conversion errors

The content of the text file is:

Dokumentnummer;Mottagnings-id;Datum;Artikel;Artikelbenämning;Batch;Löpnummer;Vikt;Volym;Antal;Enhet
183312;4393565264;2013-02-06 09:51;MERR 033 ;Mohawk Easter Rocket Red IPA ;;;;;1296.00;St
183312;4393565264;2013-02-06 09:51;MERR 033 ;Mohawk Easter Rocket Red IPA ;;;;;1296.00;St
183312;4393565264;2013-02-06 09:51;MERR 033 ;Mohawk Easter Rocket Red IPA ;;;;;768.00;St
183312;4393565264;2013-02-06 09:51;MERR300;Mohawk Easter Rocket Red IPA 30 L;;;;;24.00;St
183312;4393565264;2013-02-06 09:51;MERR300;Mohawk Easter Rocket Red IPA 30 L;;;;;24.00;St
183312;4393565264;2013-02-06 09:51;MERR300;Mohawk Easter Rocket Red IPA 30 L;;;;;2.00;St

The Wizard fails to import column no 2 (second from left) «Mottagnings-id» In the file its «4393565264».
In the table I had, to start with, datatype » double» for the column «Mottagnings-id» and had Conversion Errors.
Then I changed it to Text (255) but still get the Conversion Errors.
The I changed it to «Long Integer» (as I use for first column «Dokumentnummer» with no problems) still having the Conversion Errors.

When it comes to the column «Antal» (means number) the text file has a «.» as decimal separator, but the customer use the Scandinavian standard för decimal separtors — comma — «,» I have no Conversion Errors here .

Using the Import Wizard «manually» gives this content in the table.

3PGodsmottagning

Dokumentnummer Mottagnings-id Datum Artikel Artikelbenämning Batch Löpnummer Vikt Volym Antal Enhet
183312 2013-02-06 09:51:00 MERR 033 Mohawk Easter Rocket Red IPA 1296 St
183312 2013-02-06 09:51:00 MERR 033 Mohawk Easter Rocket Red IPA 1296 St
183312 2013-02-06 09:51:00 MERR 033 Mohawk Easter Rocket Red IPA 768 St
183312 2013-02-06 09:51:00 MERR300 Mohawk Easter Rocket Red IPA 30 L 24 St
183312 2013-02-06 09:51:00 MERR300 Mohawk Easter Rocket Red IPA 30 L 24 St
183312 2013-02-06 09:51:00 MERR300 Mohawk Easter Rocket Red IPA 30 L 2 St

— Did you write the table name correctly?

Yes its Copy and Paste

— can you give the content of sPath? Does the file exist?

— — Did you check if the file content is correct and containing a header line

Did you try to run the DoCmd command in the VBA Immediate Window?

Yes I did. Gave me 2 Error messages in a pop up window

Источник

Icon Ex Номер ошибки: Ошибка 3001
Название ошибки: Microsoft Access Error 3001
Описание ошибки: Invalid argument.
Разработчик: Microsoft Corporation
Программное обеспечение: Microsoft Access
Относится к: Windows XP, Vista, 7, 8, 10, 11

Фон «Microsoft Access Error 3001»

Эксперты обычно называют «Microsoft Access Error 3001» «ошибкой времени выполнения». Разработчики программного обеспечения пытаются обеспечить, чтобы программное обеспечение было свободным от этих сбоев, пока оно не будет публично выпущено. К сожалению, такие проблемы, как ошибка 3001, могут не быть исправлены на этом заключительном этапе.

Ошибка 3001 может столкнуться с пользователями Microsoft Access, если они регулярно используют программу, также рассматривается как «Invalid argument.». Когда появится ошибка, пользователи компьютеров смогут уведомить разработчика о наличии ошибки 3001 через отчеты об ошибках. Затем Microsoft Corporation будет иметь знания, чтобы исследовать, как и где устранить проблему. Чтобы исправить любые документированные ошибки (например, ошибку 3001) в системе, разработчик может использовать комплект обновления Microsoft Access.

Почему происходит ошибка времени выполнения 3001?

Ошибки выполнения при запуске Microsoft Access — это когда вы, скорее всего, столкнетесь с «Microsoft Access Error 3001». Следующие три наиболее значимые причины ошибок выполнения ошибки 3001 включают в себя:

Ошибка 3001 Crash — программа обнаружила ошибку 3001 из-за указанной задачи и завершила работу программы. Если данный ввод недействителен или не соответствует ожидаемому формату, Microsoft Access (или OS) завершается неудачей.

«Microsoft Access Error 3001» Утечка памяти — Ошибка 3001 утечка памяти происходит и предоставляет Microsoft Access в качестве виновника, перетаскивая производительность вашего ПК. Возможные провокации включают отсутствие девыделения памяти и ссылку на плохой код, такой как бесконечные циклы.

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

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

Ошибки Microsoft Access Error 3001

Типичные ошибки Microsoft Access Error 3001, возникающие в Microsoft Access для Windows:

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

Проблемы Microsoft Access Error 3001 с участием Microsoft Accesss возникают во время установки, при запуске или завершении работы программного обеспечения, связанного с Microsoft Access Error 3001, или во время процесса установки Windows. Важно отметить, когда возникают проблемы Microsoft Access Error 3001, так как это помогает устранять проблемы Microsoft Access (и сообщать в Microsoft Corporation).

Источник ошибок Microsoft Access Error 3001

Эти проблемы Microsoft Access Error 3001 создаются отсутствующими или поврежденными файлами Microsoft Access Error 3001, недопустимыми записями реестра Microsoft Access или вредоносным программным обеспечением.

Точнее, ошибки Microsoft Access Error 3001, созданные из:

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

Продукт Solvusoft

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

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

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

  • Remove From My Forums
  • Question

  • Hello:

    I am receiving a run time error 3001, Invalid Argument on the code illustrated below.

    One of my Access applications is an audit system for products when they are received from the factories.  I assign a new Audit number as illustrated below.

    My default DB locking options (for my client’s Access 2003) are set as follows in Tools, Options, Advanced:

    (1) Open mode is shared
    (2) Default record locking (No locks — Optimistic)
    (3) Open databases using record-level locking

    The new audit number is assigned in VBA, not on a form.  Somehow, the same number was assigned to two different audits.  The only explanation I can see is that the timing (however improbable) was that two users read it at the same time.  For
    this one file only, I want to set the ‘Pessimistic» option.  Any reason I’m getting the 3001 error on the OpenRecordset?  Before I made the change shown below, the statement for the open was:
    Set recIn = dbOpenRecordset(«tblAuditNumber») 

    ' ***********************************************************************
    ' Update And Get The Audit Number
    ' ***********************************************************************
    Set db = CurrentDb()
    Set recIn = db.OpenRecordset("tblAuditNumber", , , dbPessimistic)
    
    ' ***********************************************************************
    ' Update The Number
    ' ***********************************************************************
    recIn.Edit
    recIn!AuditNumber = recIn!AuditNumber + 1
    recIn.Update
    
    Me.txtAuditReportNumber = recIn!AuditNumber
    intGlobalAuditNumber = recIn!AuditNumber
    
    recIn.Close
    db.Close
    Set recIn = Nothing
    Set db = Nothing
    

    Rich Locus, Logicwurks, LLC

    http://www.logicwurks.com

    • Edited by

      Tuesday, November 29, 2011 11:42 PM

Answers

  • Rich, I hadn’t run into this specific problem before, but it looks to me like this is one of those cases where you have to specify all the optional arguments that precede the one that you want to override.   Try this:

        Set recIn = db.OpenRecordset(«tblAuditNumber», dbOpenTable, dbDenyWrite, dbPessimistic)

    For that, matter, I’m not sure that you need to specify dbPessimistic if you specify dbDenyWrite, though I don’t see how it could hurt.


    Dirk Goldgar, MS Access MVP
    Access tips: www.datagnostics.com/tips.html

    • Marked as answer by
      RichLocus
      Wednesday, November 30, 2011 2:43 AM

  • Remove From My Forums
  • Question

  • Hello:

    I am receiving a run time error 3001, Invalid Argument on the code illustrated below.

    One of my Access applications is an audit system for products when they are received from the factories.  I assign a new Audit number as illustrated below.

    My default DB locking options (for my client’s Access 2003) are set as follows in Tools, Options, Advanced:

    (1) Open mode is shared
    (2) Default record locking (No locks — Optimistic)
    (3) Open databases using record-level locking

    The new audit number is assigned in VBA, not on a form.  Somehow, the same number was assigned to two different audits.  The only explanation I can see is that the timing (however improbable) was that two users read it at the same time.  For
    this one file only, I want to set the ‘Pessimistic» option.  Any reason I’m getting the 3001 error on the OpenRecordset?  Before I made the change shown below, the statement for the open was:
    Set recIn = dbOpenRecordset(«tblAuditNumber») 

    ' ***********************************************************************
    ' Update And Get The Audit Number
    ' ***********************************************************************
    Set db = CurrentDb()
    Set recIn = db.OpenRecordset("tblAuditNumber", , , dbPessimistic)
    
    ' ***********************************************************************
    ' Update The Number
    ' ***********************************************************************
    recIn.Edit
    recIn!AuditNumber = recIn!AuditNumber + 1
    recIn.Update
    
    Me.txtAuditReportNumber = recIn!AuditNumber
    intGlobalAuditNumber = recIn!AuditNumber
    
    recIn.Close
    db.Close
    Set recIn = Nothing
    Set db = Nothing
    

    Rich Locus, Logicwurks, LLC

    http://www.logicwurks.com

    • Edited by

      Tuesday, November 29, 2011 11:42 PM

Answers

  • Rich, I hadn’t run into this specific problem before, but it looks to me like this is one of those cases where you have to specify all the optional arguments that precede the one that you want to override.   Try this:

        Set recIn = db.OpenRecordset(«tblAuditNumber», dbOpenTable, dbDenyWrite, dbPessimistic)

    For that, matter, I’m not sure that you need to specify dbPessimistic if you specify dbDenyWrite, though I don’t see how it could hurt.


    Dirk Goldgar, MS Access MVP
    Access tips: www.datagnostics.com/tips.html

    • Marked as answer by
      RichLocus
      Wednesday, November 30, 2011 2:43 AM

  • Remove From My Forums

 locked

Access Runtime Error 3001 invalid argument — doing a Text Import

  • Question

  • I do a Call from a procedure a Sub. Getting an error message “Runtime Error 3001 invalid argument” Pointing to this specific rows:

            ‘Import the data from sPath with the specification

           
    DoCmd.TransferText acImportDelim, «AA1», «3PGodsmottagning», _

                «C:3Pimp» & sPath, True                     

    ‘ AA1 is the Text Import Specification ‘3PGodsmottagning is the table

    In my own debugging I tried to change the name of the Text Import Specification to a non-existing one “TEST” Then I got another error message, and a understandable one
    J Runtime Error “3625” – the Textfile specification doesn’t exist. And I’m fine with that. It was just a test.

    I have used the Microsoft Methods to create the Specification:

    http://support.microsoft.com/default.aspx?scid=kb;EN-US;2581495

     I have also tried to skip the Specification name as its Optional

    SpecificationName

    Optional

    Variant

    A string expression that’s the name of an import or export specification you’ve created and saved in the current
    database. For a fixed-width text file, you must either specify an argument or use a schema.ini file, which must be stored in the same folder as the imported, linked, or exported text file. To create a schema file, you can use the text import/export wizard
    to create the file. For delimited text files and Microsoft Word mail merge data files, you can leave this argument blank to select the default import/export specifications.

      ‘Import the data from sPath with the specification        

    DoCmd.TransferText acImportDelim,  «», «3PGodsmottagning», _

                «C:3Pimp» & sPath, True

    Running this gave me another Error message “Runtime Error 3270” property not found.

    Obviously something or me is wrong. But what?


    Best Peter Forss

    • Edited by

      Friday, May 31, 2013 6:20 AM

Answers

  • Hurra!

    I found it! 

    I made a new Import Specification. This time I did it without saying «first line contains fieldnames»!!

    ‘Import the data from sPath with the specification
            DoCmd.TransferText acImportDelim, «Godsmottagning_108», «3P Godsmottagning», _
                «C:3Pimp» & sPath, True

    The HasFieldNames = «True» in the code line above does that part.

    Now it runs exactly as I like it to.
    Thanks Henry for supporting me.

    The new code is:

    Sub DailyImport3P()
    Dim rs As Recordset
    Dim sql As String
    Dim db As Database
    Set db = CurrentDb()

    Dim sPath As String
    sPath = Dir$(«C:3Pimp» & «*.txt», vbNormal)
    Debug.Print sPath
    Do Until sPath = «»
        sql = «SELECT * From 3PimporteradefilerGodsmottagning Where FileName='» & sPath & «‘»
        Set rs = CurrentDb.OpenRecordset(sql)

        
        ‘Check if the file name existing or not
        If rs.RecordCount = 0 Then

        
            ‘Import the data from sPath with the specification
            DoCmd.TransferText acImportDelim, «Godsmottagning_108», «3P Godsmottagning», _
                «C:3Pimp» & sPath, True
                Debug.Print sPath

            
            ‘Insert Filename not table
            sql = «Insert Into 3PimporteradefilerGodsmottagning (FileName) Values(‘» & sPath & «‘)»
            CurrentDb.Execute sql
            rs.Close
            Set rs = Nothing
            Set db = Nothing
        End If
        sPath = Dir$
    Loop

    End Sub


    Best Peter Forss

    • Marked as answer by
      ForssPeterNova
      Wednesday, June 5, 2013 6:24 PM

У меня есть таблица Excel, и я хочу обновить значение даты в записях таблицы SQL Server (с функцией getdate), указанное в 12-м столбце Excel.

Мой код такой, как показано ниже, но я вижу:

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

В таблице SQL поле MODIFIEDDATE имеет тип datetime, а поле MAINREF — целочисленный тип.

Private Sub CommandButton2_Click()

Dim conn2 As New ADODB.Connection
Dim rst2 As New ADODB.Recordset
Dim j As Integer

conn2.ConnectionString = "Provider=SQLOLEDB.1;Password=abc;Persist Security Info=True;User ID=sa;Initial Catalog=logodb;Data Source=A3650;Use Procedure for Prepare=1;Auto"
conn2.Open

For j = 0 To 1900
    If Sayfa1.Cells(j + 4, 12) = "" Then
        Sayfa1.Cells(j + 4, 13) = "empty"
    Else
        rst2.Open "UPDATE T_015 SET MODIFIEDDATE=GETDATE() WHERE MAINREF='" & Sayfa1.Cells(j + 4, 12) & "'", conn, 1, 3
        rst2.Close
    End If
Next j

End Sub

Я пытался изменить SQL-запрос, например (CInt (cell.value))

rst2.Open "UPDATE T_015 SET MODIFIEDDATE=GETDATE() WHERE MAINREF='" & CInt(Sayfa1.Cells(j + 4, 12)) & "'", conn, 1, 3

Но это не сработало.

2 ответа

Лучший ответ

Объект ADODB.Recordset не следует использовать для запроса UPDATE. Выполните инструкцию SQL прямо из ADODB.Connection

Dim conn2 As New ADODB.Connection

conn2.ConnectionString = "Provider=SQLNCLI11;Server=MYSERVER;Database=TMP;UID=sa;password=abc;"
conn2.Open

conn2.Execute "UPDATE T_015 SET MODIFIEDDATE=GETDATE() WHERE MAINREF=1"

Есть несколько способов выполнить свои требования, и кажется, что вы смешиваете их.

Один из способов — обновлять записи по одной, и для этого вы можете использовать объект Connection или, что более предпочтительно, объект Command. Я говорю «предпочтительно», потому что параметризованные команды — гораздо более надежный способ выполнения вашего SQL. Если вы собираетесь использовать SQL, то вам, вероятно, следует прочитать об этом. Это можно сделать следующим образом:

Public Sub ParameterisedProcedure()
    Dim conn As ADODB.Connection
    Dim cmd As ADODB.Command
    Dim prm As ADODB.Parameter
    Dim v As Variant
    Dim j As Integer

    'Read the sheet data
    v = Sayfa1.Range("L4", "M1904").Value2

    'Open the database connection
    Set conn = New ADODB.Connection
    conn.ConnectionString = "Provider=SQLOLEDB.1;" & _
                              "Password=abc;" & _
                              "Persist Security Info=True;" & _
                              "User ID=sa;" & _
                              "Initial Catalog=logodb;" & _
                              "Data Source=A3650;" & _
                              "Use Procedure for Prepare=1;" & _
                              "Auto"
    conn.Open

    'Loop through the values to update records
    For j = 1 To UBound(v, 1)
        If IsEmpty(v(j, 1)) Then
            v(j, 2) = "empty"
        Else
            'Create the parameterised command
            Set cmd = New ADODB.Command
            cmd.ActiveConnection = conn
            cmd.CommandType = adCmdText
            cmd.CommandText = "UPDATE T_015 " & _
                              "SET MODIFIEDDATE=? " & _
                              "WHERE MAINREF=?"
            prm = cmd.CreateParameter(Type:=adDate, Value:=Now)
            cmd.Parameters.Append prm
            prm = cmd.CreateParameter(Type:=adInteger, Value:=v(j, 1))
            cmd.Parameters.Append prm
            cmd.Execute
        End If
    Next

    'Write the updated values
    Sayfa1.Range("L4", "M1904").Value = v

    'Close the database
    Set prm = Nothing
    Set cmd = Nothing
    conn.Close

End Sub

Другой способ — использовать Transactions, и вы действительно использовали бы для этого Recordset (т.е. аналогично тому, что вы уже сделали). В этом случае я бы предположил, что это лучший способ сделать это, потому что выполнение одной команды за раз (как в приведенном выше коде) очень медленно. Намного более быстрый способ — зафиксировать все ваши обновления в одной транзакции. Как и параметризованная команда, она также защищена от ввода неверных строк в текст вашей команды SQL. Код будет выглядеть так:

Public Sub TransactionProcedure()
    Dim conn As ADODB.Connection
    Dim rs As ADODB.Recordset
    Dim cmdText As String
    Dim v As Variant
    Dim j As Integer

    'Read the sheet data
    v = Sayfa1.Range("L4", "M1904").Value2

    'Open the database connection
    Set conn = New ADODB.Connection
    conn.ConnectionString = "Provider=SQLOLEDB.1;" & _
                              "Password=abc;" & _
                              "Persist Security Info=True;" & _
                              "User ID=sa;" & _
                              "Initial Catalog=logodb;" & _
                              "Data Source=A3650;" & _
                              "Use Procedure for Prepare=1;" & _
                              "Auto"
    conn.Open

    'Retrieve the data
    Set rs = New ADODB.Recordset
    cmdText = "SELECT * FROM  T_015"
    rs.Open cmdText, conn, adOpenStatic, adLockReadOnly, adCmdText

    'Loop through the values to update the recordset
    On Error GoTo EH
    conn.BeginTrans
    For j = 1 To UBound(v, 1)
        If IsEmpty(v(j, 1)) Then
            v(j, 2) = "empty"
        Else
            'Find and update the record
            rs.Find "MAINREF=" & CStr(v(j, 1))
            If Not rs.EOF Then
                rs!ModifiedDate = Now
                rs.Update
            End If
        End If
    Next
    conn.CommitTrans

    'Write the updated values
    Sayfa1.Range("L4", "M1904").Value = v

    'Close the database
    rs.Close
    conn.Close
    Exit Sub

EH:
    conn.RollbackTrans
    Sayfa1.Range("L4", "M1904").Value = v
    rs.Close
    conn.Close
    MsgBox Err.Description
End Sub


0

Ambie
17 Ноя 2015 в 12:55

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

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

  • Ошибочный антоним к этому слову
  • Ошибочный код сброса пароля что это
  • Ошибочный анализ на гонорею
  • Ошибочный код сброса пароля sirus
  • Ошибочный анализ на вич причины

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

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