Ошибка runtime error 3001

  • 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

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:

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

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:

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

The job of ConnectDB is to create a database connection. Instead of assigning to some oConn object (which may already be connected and opened) declared in another scope, make it a Function.

Private Function ConnectDB() As ADODB.Connection
    Dim conn As ADODB.Connection
    Set conn = New ADODB.Connection

    Const connString As String = _
      "DRIVER={MySQL ODBC 5.1 Driver};" & _
      "SERVER=XXX.XXX.XXX.XXX;" & _
      "PORT=3306l" & _
      "DATABASE=myDB;" & _
      "USER=User;" & _
      "PASSWORD=pwd;" & _
      "Option=3"

    On Error GoTo CleanFail
    conn.Open connString
    Set ConnectDB = conn
    Exit Function
CleanFail:
    Debug.Print "Error opening database connection:"
    Debug.Print Err.Number, Err.Description
    Debug.Print "ConnectDB is returning Nothing."
    Set ConnectDB = Nothing
End Function

Now you have a function that either connects and returns a live ADODB.Connection, or doesn’t and returns Nothing instead — and all values involved aren’t scoped any wider than they need to be.

So InsertData can now use it. Now, we don’t need a Recordset at all — we don’t care about any records, we just want to run an INSERT query; this can run against the connection itself — note that the number of VALUES must match the number of columns specified in the INSERT INTO clause… and since a hard-coded set of values isn’t very useful, you’ll want these values properly parameterized (DO NOT concatenate worksheet cell values into your SQL statement — meet Little Bobby Tables):

Public Sub InsertData(ByVal emplacement As String, ByVal etage As String, ByVal colonne As String, ByVal taille As String)
    Dim conn As ADODB.Connection
    Set conn = ConnectDB
    If conn Is Nothing Then
        ' couldn't connect to database; review Debug output, fix connection string.
        MsgBox "Could not connect to database.", vbExclamation
        Exit Sub
    End If

    Const sql As String = _
        "INSERT INTO Position (Emplacement, Etage, Colonne, Taille) " &
        "VALUES(?, ?, ?, ?) "

    Dim cmd As ADODB.Command
    Set cmd = New ADODB.Command

    Set cmd.ActiveConnection = conn
    cmd.CommandType = adCmdText
    cmd.CommandText = sql

    'TODO: verify parameter types & sizes.
    'NOTE: parameters must be added in the order they are specified in the SQL.
    cmd.Parameters.Append cmd.CreateParameter(Type:=adVarWChar, Size:=200, Value:=emplacement)
    cmd.Parameters.Append cmd.CreateParameter(Type:=adVarWChar, Size:=200, Value:=etage)
    cmd.Parameters.Append cmd.CreateParameter(Type:=adVarWChar, Size:=200, Value:=colonne)
    cmd.Parameters.Append cmd.CreateParameter(Type:=adVarWChar, Size:=200, Value:=taille)

    On Error GoTo CleanFail
    cmd.Execute '<~ when you DO need a recordset, this gets you your recordset.
CleanExit:
    conn.Close
    Exit Sub
CleanFail:
    Debug.Print "Error executing command: " & sql
    Debug.Print Err.Number, Err.Description
    Resume CleanExit
End Sub

Содержание

  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

Источник

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

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

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

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

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

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

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

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

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

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

Если метод ремонта вам подошел, пожалуйста, нажмите кнопку 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 3001 (Microsoft Access Error 3001) — Invalid argument.
Wie beheben Fehler 3001 (Microsoft Access-Fehler 3001) — Ungültiges Argument.
Come fissare Errore 3001 (Errore di Microsoft Access 3001) — Argomento non valido.
Hoe maak je Fout 3001 (Microsoft Access-fout 3001) — Ongeldig argument.
Comment réparer Erreur 3001 (Erreur d’accès Microsoft 3001) — Argument invalide.
어떻게 고치는 지 오류 3001 (마이크로소프트 액세스 오류 3001) — 잘못된 인수입니다.
Como corrigir o Erro 3001 (Erro 3001 do Microsoft Access) — Argumento inválido.
Hur man åtgärdar Fel 3001 (Microsoft Access Error 3001) — Ogiltigt argument.
Jak naprawić Błąd 3001 (Błąd Microsoft Access 3001) — Błędny argument.
Cómo arreglar Error 3001 (Error 3001 de Microsoft Access) — Argumento no válido.

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

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

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

10/08/22 05:29 : Пользователь Windows 10 проголосовал за то, что метод восстановления 1 работает для него.

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

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

ШАГ 1:

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

ШАГ 2:

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

ШАГ 3:

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

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

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

Требования

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

ID статьи: ACX06381RU

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

Совет по увеличению скорости #35

Использование ReadyBoost для увеличения скорости:

ReadyBoost, представленный в Windows 7, может мгновенно ускорить работу вашей системы, просто подключив USB-накопитель. Это может дать вам дополнительную оперативную память для работы. Эта функция может повысить скорость открытия приложений и увеличить время загрузки.

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

Icon Ex Error Number: Error 3001
Error Name: Microsoft Access Error 3001
Error Description: Invalid argument.
Developer: Microsoft Corporation
Software: Microsoft Access
Applies to: Windows XP, Vista, 7, 8, 10, 11

Microsoft Access Error 3001 Background

Experts generally refer to Microsoft Access Error 3001 as a «runtime error». Software developers try to ensure software are free from these glitches until it is publicly released. Regrettably, issues such as error 3001 might not get fixed at this final stage.

Error 3001 might be faced by Microsoft Access users if they are using the program regularly, also seen as «Invalid argument.». When the bug shows up, computer users will be able to notify the developer about the presence of error 3001 through error reporting. Microsoft Corporation will then have the knowledge to investigate how and where to fix the issue. In order to correct any documented errors (like error 3001) in the system, the developer can make use of a Microsoft Access update kit.

Why Does Runtime Error 3001 Happen?

Execution faults at the startup of Microsoft Access is when you’re most likely to run into Microsoft Access Error 3001. The following three most significant causes of error 3001 runtime errors include:

Error 3001 Crash — The program encountered an error 3001 error because of a specified task, and terminated the program. When the given input is invalid or does not adhere to the format expected, Microsoft Access (or OS) fails.

Microsoft Access Error 3001 Memory Leak — Error 3001 memory leak occurs and exposes Microsoft Access as a culprit, dragging down your PC performance. Possible provocations include lack of memory de-allocation and having reference to bad code such as infinite loops.

Error 3001 Logic Error — A logic error occurs when the machine generates the incorrect output, even when the user provides the right input. Usual causes of this problem are due to faults in data handling.

Commonly, corrupt or missing Microsoft Access Error 3001 files cause these Microsoft Corporation errors, and are sometimes attributed to a current or past malware infection affecting Microsoft Access. Although annoying, these issues can usually be easily remedied through replacing the problem Microsoft Corporation file. As a supplemental troubleshooting step, we highly recommend cleaning up any invalid file path and Microsoft Corporation file extension references that could contribute to creating these Microsoft Access Error 3001 error messages.

Microsoft Access Error 3001 Errors

Typical Microsoft Access Error 3001 Errors That Occur in Microsoft Access for Windows:

  • «Microsoft Access Error 3001 Error.»
  • «Win32 Software Error: Microsoft Access Error 3001»
  • «Microsoft Access Error 3001 has encountered a problem and needs to close. We are sorry for the inconvenience.»
  • «Cannot find Microsoft Access Error 3001.»
  • «Microsoft Access Error 3001 can’t be found.»
  • «Error starting program: Microsoft Access Error 3001.»
  • «Can’t run Microsoft Access Error 3001.»
  • «Microsoft Access Error 3001 quit.»
  • «Microsoft Access Error 3001: App Path is Faulting.»

Microsoft Access-involved Microsoft Access Error 3001 issues happen during install, when Microsoft Access Error 3001-related software is running, startup or shutdown, or during the Windows installation process. It’s important to note when Microsoft Access Error 3001 issues happen, as it helps troubleshoot Microsoft Access problems (and report to Microsoft Corporation).

Source of Microsoft Access Error 3001 Errors

These Microsoft Access Error 3001 troubles are created by missing or corrupt Microsoft Access Error 3001 files, invalid Microsoft Access registry entries, or malicious software.

More precisely, Microsoft Access Error 3001 errors created from:

  • Invalid Microsoft Access Error 3001 or corrupted registry key.
  • Microsoft Access Error 3001 file corrupted from virus infection.
  • Microsoft Access Error 3001 maliciously, or mistakenly, removed by another software (apart from Microsoft Access).
  • Another software in conflict with Microsoft Access, Microsoft Access Error 3001, or shared references.
  • Corrupt download or incomplete installation of Microsoft Access software.

Product by Solvusoft

Download Now
WinThruster 2022 — Scan your PC for computer errors.

Compatible with Windows 11, 10, 8, 7, Vista, XP and 2000

Optional Offer for WinThruster by Solvusoft | EULA | Privacy Policy | Terms | Uninstall

My code is as below, but I’m seeing:
In SQL table MODIFIEDDATE field is datetime type, and MAINREF field is integer type.
Question:
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.

Table of contents

  • Runtime error 3001 ‘Arguments are of the wrong type or out of acceptable range…’
  • Runtime error 3001 ‘Arguments are of the wrong type or out of acceptable range…’ INSERT INTO MySQL Database
  • Runtime error 3001 when using ADO Recordset.Find with more than one criteria
  • What causes run-time error’3001’in access?
  • What does run-time error 3061 mean?
  • What causes run-time error 3021 no current record?

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


Question:

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.

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

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

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

but, it didn’t work.


Solution 1:

The adodb.recordset object should not be used for an UPDATE query. Execute the SQL statement directly from the 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"


Solution 2:

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:

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

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:

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

Ms access — Runtime error 3001 when using ADO, I am trying to use the recordset.Find «name =» &amp; me.txtbox.value. To find a particular record/row. I can do this quite easily if i do it exactly as above searching only with 1 variable. I trie

Runtime error 3001 ‘Arguments are of the wrong type or out of acceptable range…’ INSERT INTO MySQL Database


Question:

I know there is lot of question of the same type but no one helped me and I’am really stuck.
So I’am trying to send Data from an Excel table with VBA and I always get the same error : ‘Runtime error 3001 ‘Arguments are of the wrong type or out of acceptable range’
The thing is i can’t understand where my mistake comes from ? Is it from my SQL query or from the visual basic code ?
My code is in 3 sub

Dim oConn As ADODB.Connection

the second one

Private Sub ConnectDB()
    Set oConn = New ADODB.Connection
    Dim str As String
    str = "DRIVER={MySQL ODBC 5.1 Driver};" & _
          "SERVER=XXX.XXX.XXX.XXX" & ";" & _
          "PORT=3306" & ";" & _
          "DATABASE=myDB" & ";" & _
          "USER=User" & ";" & _
          "PASSWORD=pwd" & ";" & _
          "Option=3"
    ''' error '''
    oConn.Open str
End Sub

And the last one

Sub InsertData()    
    Dim Rs As ADODB.Recordset
    Dim Requete As String
    Set Rs = New ADODB.Recordset
    Call ConnectDB
    With Sheets("Feuil5")
        Requete = "INSERT INTO Position (Emplacement,Etage,Colonne,Taille) VALUES ('1','1','1','1');"
        Rs.Open Requete, oConnect, adOpenDynamic, adLockOptimistic
    End With
    Debug.Print Requete
    oConnect.Close
    Set Rs = Nothing
End Sub

Could someone find my mistake and help realisyzing and simple sql query in vba ?


Solution 1:

The job of

ConnectDB

is to create a database connection. Instead of assigning to some

oConn

object (which may already be connected and opened) declared in another scope, make it a

Function

.

Private Function ConnectDB() As ADODB.Connection
    Dim conn As ADODB.Connection
    Set conn = New ADODB.Connection
    Const connString As String = _
      "DRIVER={MySQL ODBC 5.1 Driver};" & _
      "SERVER=XXX.XXX.XXX.XXX;" & _
      "PORT=3306l" & _
      "DATABASE=myDB;" & _
      "USER=User;" & _
      "PASSWORD=pwd;" & _
      "Option=3"
    On Error GoTo CleanFail
    conn.Open connString
    Set ConnectDB = conn
    Exit Function
CleanFail:
    Debug.Print "Error opening database connection:"
    Debug.Print Err.Number, Err.Description
    Debug.Print "ConnectDB is returning Nothing."
    Set ConnectDB = Nothing
End Function

Now you have a function that either connects and returns a live

ADODB.Connection

, or doesn’t and returns

Nothing

instead — and all values involved aren’t scoped any wider than they need to be.

So

InsertData

can now use it. Now, we don’t need a

Recordset

at all — we don’t care about any records, we just want to run an

INSERT

query; this can run against the connection itself — note that the number of

VALUES

must match the number of columns specified in the

INSERT INTO

clause… and since a hard-coded set of values isn’t very useful, you’ll want these values properly parameterized (DO NOT concatenate worksheet cell values into your SQL statement — meet

Little Bobby Tables

):

Public Sub InsertData(ByVal emplacement As String, ByVal etage As String, ByVal colonne As String, ByVal taille As String)
    Dim conn As ADODB.Connection
    Set conn = ConnectDB
    If conn Is Nothing Then
        ' couldn't connect to database; review Debug output, fix connection string.
        MsgBox "Could not connect to database.", vbExclamation
        Exit Sub
    End If
    Const sql As String = _
        "INSERT INTO Position (Emplacement, Etage, Colonne, Taille) " &
        "VALUES(?, ?, ?, ?) "
    Dim cmd As ADODB.Command
    Set cmd = New ADODB.Command
    Set cmd.ActiveConnection = conn
    cmd.CommandType = adCmdText
    cmd.CommandText = sql
    'TODO: verify parameter types & sizes.
    'NOTE: parameters must be added in the order they are specified in the SQL.
    cmd.Parameters.Append cmd.CreateParameter(Type:=adVarWChar, Size:=200, Value:=emplacement)
    cmd.Parameters.Append cmd.CreateParameter(Type:=adVarWChar, Size:=200, Value:=etage)
    cmd.Parameters.Append cmd.CreateParameter(Type:=adVarWChar, Size:=200, Value:=colonne)
    cmd.Parameters.Append cmd.CreateParameter(Type:=adVarWChar, Size:=200, Value:=taille)
    On Error GoTo CleanFail
    cmd.Execute '<~ when you DO need a recordset, this gets you your recordset.
CleanExit:
    conn.Close
    Exit Sub
CleanFail:
    Debug.Print "Error executing command: " & sql
    Debug.Print Err.Number, Err.Description
    Resume CleanExit
End Sub


Solution 2:

Okey so to solve this problem I added all in one sub and here what I have know :

Private Sub ConnectDB()
Dim oConn As ADODB.Connection
Set oConn = New ADODB.Connection
Dim Rs As ADODB.Recordset
Dim Requete As String
Set Rs = New ADODB.Recordset
Dim S As String
S = "DRIVER={MySQL ODBC 5.1 Driver};" & _
      "SERVER=XXX.XXX.XXX.XXX" & ";" & _
      "PORT=3306" & ";" & _
      "DATABASE=x" & ";" & _
      "USER=x" & ";" & _
      "PASSWORD=x" & ";" & _
      "Option=3"
''' error '''
oConn.Open S
Requete = "INSERT INTO Position(Emplacement,Etage,Colonne,Taille) VALUES('test','test','test','test');"
    Rs.Open Requete, oConn, adOpenDynamic, adLockOptimistic
    Debug.Print Requete
    oConn.Close
    Set Rs = Nothing
End Sub

It solved my initial problem but now I get another problem ( Execution error’-2147217887 (80040e21)’:
This driver does not support the requested properties ) but anyway thanks for your help I’am going to try to find my other mistake now.
Have a nice day

Run-time error ‘3061’. Too few parameters. Expected 1, Too few parameters, expected X means that X fieldnames that you’ll using in your SQL-Statement aren’t available. Mostly typos when writing down lines of SQL Code by hand, mostly when you’re using DBs which can have multiple «versions» of it, one DB has those fields, one DB hasn’t.

Runtime error 3001 when using ADO Recordset.Find with more than one criteria


Question:

I am trying to use the

recordset.Find "name =" & me.txtbox.value

. To find a particular record/row. I can do this quite easily if i do it exactly as above searching only with 1 variable.

I tried to do the follow as i found other have done this online.

traceRecordset.Find "[PART_ID]=" & Me.txtSection.Value & " AND " & "[ID]= " & Me.txtCopy.Value

this is the exact line of code that follows, the error does not throw on this line

Me.txtLastscrap = traceRecordset.Fields("APROPERTY_2")

This would give me more flexibility when populating a textbox with a particular value. It seems others have attempted this with no issues. However, i receive the following error.

Arguments are of the wrong type, are out of acceptable
range or are in conflict with one another

Any thoughts?

NOTE: if i do

traceRecordset.Find "[PART_ID]=" & Me.txtSection.Value

it works and it also works with

traceRecordset.Find "[ID]= " & Me.txtCopy.Value

so individually they function correctly. Only when used together does it throw an error. If the types were the issue one of them would not work when used independently correct?

NOTE2: Here is my adodb connection line. Not sure if this has any effect


Dim dbTrace As ADODB.Connection
Dim traceRecordset As New ADODB.Recordset


Set dbTrace = CurrentProject.Connection
traceRecordset.Open "Select * from TRACE", _
dbTrace, adOpenKeyset, adLockOptimistic, adCmdText


Solution:

According to the ADO recordset.find documentation,


Only a single-column name may be specified in criteria. This method
does not support multi-column searches.


Criteria

:
A String value that contains a statement specifying the column name, comparison operator, and value to use in the search.


Since you are already writing VBA within an Access project, DAO works just as well and as of Access 2016, the DAO Recordset type is still the default used by Forms and QueryDef objects. DAO recordsets support FindFirst, FindNext, FindPrevious and FindLast all supporting multi-column queries. This single feature might not justify switching from ADO, but if all you’re doing is opening, searching and enumerating recordset rows, ADO doesn’t provide any significant benefit.

Error 3001 (arguments are of wrong type) when quering, Teams. Q&A for work. Connect and share knowledge within a single location that is structured and easy to search. Learn more

Read other technology post:
Introducing Pair Programming


  • Ошибка runtime error 217 at 004bb10d autodata как исправить
  • Ошибка runtime error 203
  • Ошибка runtime error 13 type mismatch как исправить
  • Ошибка runscript при установке 1с
  • Ошибка running gear fault service now на туареге