I have a copy of an Access database that is meant for importing discontinued product data from a .csv file into a SQL Server database (by using linked tables). When I initiate this import process, I get the following macro error:
I looked up the 2001 Error Number and have seen a few different explanations of it. Mainly, that I need to add the location of the database as a trusted location. I have done that, but that hasn't made a difference.
I noticed I can also see what code the problem occurs in, the "ImportDiscontinued()" function which looks like this:
Public Function ImportDiscontinued()
Dim sImpSpec As String
Dim sImpTable As String
Dim sPath As String
Dim sFile As String
Dim db As Database
Dim rsOption As Recordset
Dim rs As Recordset
Set db = CurrentDb
Set rsOption = db.OpenRecordset("SELECT tblOptions.zValue FROM tblOptions WHERE (((tblOptions.zOption)='ImportPath'));")
sPath = rsOption.Fields("zValue")
Set rsOption = Nothing
If Right(sPath, 1) <> "\" Then
sPath = sPath & "\"
End If
sImpSpec = "DiscontinuedItemMaster Import Specification"
sImpTable = "tblDiscontinuedCurrent"
sFile = sPath & "DiscontinuedItemMaster.csv"
DoCmd.SetWarnings False
DoCmd.OpenQuery "dqDiscontinuedCurrent"
DoCmd.OpenQuery "dqObsDiscontinuedDuplicates"
DoCmd.TransferText acImportDelim, sImpSpec, sImpTable, sFile, True
DoCmd.OpenQuery "dqDiscontinuedCurrent_Blanks"
DoCmd.OpenQuery "uqObsDiscontinuedCurrent_SameProdRepl"
DoCmd.OpenQuery "uqObsDiscontinuedCurrent_Trim"
DoCmd.OpenQuery "uqObsDiscontinuedCurrent"
DoCmd.OpenQuery "aqObsDiscontinuedDuplicates"
DoCmd.SetWarnings True
Set rs = db.OpenRecordset("dbo_tmpObsDiscontinued_Duplicates")
If rs.EOF Then
MsgBox "New Discontinued Items Have Imported Successfully! You may now process...", vbInformation + vbOKOnly, "Success!"
Else
MsgBox "Duplicates were found!. They will now be removed...", vbCritical + vbOKOnly, "Error"
DoCmd.RunMacro "mcObsDiscontinuedDuplicates"
End If
Set rsOption = Nothing
Set rs = Nothing
db.Close
End Function
But looking at it, I can't really see where things could be going wrong. I noticed I can set breakpoints, but they don't seem to get hit.
I know that the connection to the SQL Server database is OK because I am initially prompted for credentials and then I am able to view the data through the linked table just fine.
A disclaimer that I am only really familiar with the basics of Access so macros and coding in VBA is all new to me. I typically work with SQL Server databases and programming in C#.
EDIT: Here is the macro "mcObsDiscontinuedImport":
Related
I'm using Access 2013 as a front end with a SQL Server back end, and I'm trying to bind an ADO Recordset to a form, however, the Recordset will only open as Static. So I can see all the records in a datasheet, I just can't edit them.
I can use the connection object to execute an update query, so I don't think that is the issue. I've tried using Dynamic, Keyset and Forward-Only and locking as Batch Optimistic, Optimistic, and Pessimistic to open the Recordset, but still opens as static.
Below code is condensed, but essentially the same, and most importantly, still doesn't work.
Public Sub TestConnect()
Dim objConn As ADODB.Connection
Dim objRS As ADODB.Recordset
Set objConn = New ADODB.Connection
objConn.ConnectionString = "Data Provider=sqloledb;Provider=Microsoft.Access.OLEDB.10.0;Server=REDACTED;Database=REDACTED;Trusted_Connection=Yes"
objConn.CursorLocation = adUseClient
objConn.Open
Debug.Print objConn.state = adStateOpen
Set objRS = New ADODB.Recordset
objRS.CursorLocation = adUseClient
objRS.Open "SELECT * FROM Table1;", objConn, adOpenDynamic, adLockOptimistic
Debug.Print objRS.CursorType
objRS.Close
objConn.Close
End Sub
I've tried looking at a few place, such as https://learn.microsoft.com/en-us/office/vba/access/Concepts/ActiveX-Data-Objects/bind-a-form-to-an-ado-recordset and MS Access Form Bound to ADO Disconnected Recordset, but I'm not having any luck identifying where my issue is.
Any help would be amazing, I'm tearing my hair out here. Thanks!
I have to import data from Excel into a SQL Server database.
I am getting Excel files via email daily. I have to get them out from email and put the contents into the database. Also, I want to automate it instead of doing it manually.
I am thinking of below ideas:
Fetching the email attachment out of the inbox (automated process using some tool etc.) and save it to say the O: drive (then it's simple to pull into the database from there)
Taking help of any tool available (open source) and get the Excel content into SQL Server directly from the inbox.
I hope that makes sense about what I am trying to do.
Can someone please tell me how to automate this?
Thanks,
AP
You can use VBA for everything here.
1) Download attachments from Outlook.
Public Sub SaveAttachmentsToDisk(MItem As Outlook.MailItem)
Dim oAttachment As Outlook.Attachment
Dim sSaveFolder As String
sSaveFolder = "C:\Users\DT168\Documents\outlook-attachments\"
For Each oAttachment In MItem.Attachments
oAttachment.SaveAsFile sSaveFolder & oAttachment.DisplayName
Next
End Sub
2) Load data from Excel file(s) into SQL Server.
Sub InsertARecord()
Dim cnt As ADODB.Connection
Dim rst As ADODB.Recordset
Dim stCon As String, stSQL As String
Set cnt = New ADODB.Connection
Set rst = New ADODB.Recordset
stCon = "Provider=MSDASQL.1;Persist Security Info=False;Data Source=JOEY"
cnt.ConnectionString = stCon
stSQL = "INSERT INTO MyTable (FieldNames)"
stSQL = stSQL & "VALUES (ActualValues)"
stSQL = stSQL & "WHERE lockStatus = 'nolock'"
cnt.Open
rst.Open stSQL, cnt, adOpenStatic, adLockReadOnly, adCmdText
If CBool(rst.State And adStateOpen) = True Then rst.Close
Set rst = Nothing
If CBool(cnt.State And adStateOpen) = True Then cnt.Close
Set cnt = Nothing
End Sub
Also, see this URL.
https://www.excel-sql-server.com/excel-sql-server-import-export-using-vba.htm#Introduction
The process is run in the environment of Excel VBA 2010 and MS SQL Server 2008.
Assume that there is a simple one column data with 1500 rows in an Excel-sheet and we want to export it to the database with SQL-queries in VBA code (SQL procedure in VBA exports maximum 1000 rows at once in default mode).
There is one limitation in this problem: the export procedure must be with dbclass-connection instead of ADODB connection. (The code-owner is not me. The code-owner is using dbclass for a quite big VBA code, so probably he wouldn't accept to change the whole code).
I found an option like lngRecsAff for ADODB.Connection which is used like:
Sub test()
Dim cn As ADODB.Connection
Dim strSQL As String
Dim lngRecsAff As Long
Set cn = New ADODB.Connection
cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\test.xls; Extended Properties=Excel 8.0"
strSQL = "Insert INTO [odbc;Driver={SQL Server};Server=SQL09;Database=Tom;UID=userID;PWD=password].tbl_test1 Select * FROM [Sheet1$]"
cn.Execute strSQL, lngRecsAff
cn.Close
Set cn = Nothing
End Sub
I tried to implement that lngRecsAff in my dbclass execution like:
Sub test()
Dim connOk As Boolean
Dim rs As New ADODB.Recordset
Set dbclass = New clsDB
Dim Value1() As Variant
Dim lngRecsAff As Long
Dim strSQL as String
Dim mstrErr as Boolean
dbclass.Database = "database_name"
dbclass.ConnectionType = SqlServer
dbclass.DataSource = "server_name"
dbclass.UserID = Application.UserName
connOk = dbclass.OpenConnection(False, True)
If connOk = False Then
MsgBox "Unsuccessful connection!"
Else
MsgBox "Successful connection"
End If
strSQL = "INSERT INTO [dbo].[table1](Column1) Values('" & Value1 & "')"
mstrErr = dbclass.ExecuteSQL(strSQL, lngRecsAff) ' The result mstrErr is a Boolean
' Some closing options here
End Sub
I got en error like lngRecsAff is not suitable for my ExecuteSQL procedure. Normally my execution mstrErr = dbclass.ExecuteSQL(strSQL) works without any problem.
Maybe I can do the SQL-procedure with a for-loop, then I can send the data in small pieces. But I want to find a more efficient, "nicer" solution which sends the whole array at once.
So is there any special option for dbclass which can send more than 1000 rows from Excel to the database?
You can query the Excel-Sheet directly using liked server.
In your Management Studio click to "Server Objects" and then right click onto "linked server". There you'll be able to add a new linked server.
If you need further help you can find tuorials easily. One is here:
https://www.mssqltips.com/sqlservertip/2018/using-a-sql-server-linked-server-to-query-excel-files/
I am doing an excel macro in order to automate some query what eventually I run in SQL Server. My problem is that I don't know how the server could alert excel if a query did not succeed.
For example, I am importing a file, and there is no syntax error, but it might result in error if bulk insert statement is not set properly. For the SQL connection I use the following:
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=localhost;" & _
"Initial Catalog=" & MyDatabase & ";" & _
"Integrated Security=SSPI;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
conn.Open sConnString
Set rs = conn.Execute(Myquery)
If I have a syntax error while compiling the code it stops which is good. But if I have another problem, e. g. the database name is not good, the table already exists, then the program runs with no error, I only can detect when I check it in SQL Server. I really want to know somehow whether the query run has resulted in error and then code some alerting message then into my macro. How can I do that?
Every help is much appreciated!
The ADO connection object has an Errors collection, which you can check after running your SQL:
conn.Errors.Clear
Set rs = conn.Execute(Myquery)
If conn.Errors.Count > 0 Then
For i = 0 To conn.Errors.Count
Debug.Print conn.Error(i).Number
Debug.Print conn.Error(i).Source
Debug.Print conn.Error(i).Description
next i
End If
That should get you started. You may find that you're seeing an 'error zero' that's actually a status message; if so, you'll have some additional coding to to do.
I found this helpful but needed to use:
Debug.Print conn.Errors.Item(i).Description
Debug.Print conn.Errors.Item(i).Source
Debug.Print conn.Errors.Item(i).NativeError
I might be using a different connection type
HI
I want to find a particular field, which exist in tables of a Access database. Is there is any utility to find this?
Yes you can do it VBA code. I have emailed you.
Public Function FindField(fieldname As String)
Dim db As Database
Dim td As TableDef
Dim fd As Field
Set db = DBEngine(0)(0)
db.TableDefs.Refresh
For Each td In db.TableDefs
For Each fd In td.fields
If fieldname = fd.Name Then
Debug.Print td.Name
End If
Next
Next
db.Close
End Function
You can use ADO Schemas:
Function ListTablesContainingField(SelectFieldName) As String
''Tables returned will include linked tables
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strTempList As String
On Error GoTo Error_Trap
Set cn = CurrentProject.Connection
''Get names of all tables that have a column called <SelectFieldName>
Set rs = cn.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, Empty, SelectFieldName))
''List the tables that have been selected
While Not rs.EOF
''Exclude MS system tables
If Left(rs!Table_Name, 4) <> "MSys" Then
strTempList = strTempList & "," & rs!Table_Name
End If
rs.MoveNext
Wend
ListTablesContainingField = Mid(strTempList, 2)
Exit_Here:
rs.Close
Set cn = Nothing
Exit Function
Error_Trap:
MsgBox Err.Description
Resume Exit_Here
End Function
See also: http://support.microsoft.com/kb/186246
I do a lot of maintenance and integration work in access and a vba module written by Allen Browne totally rocks.
In your immediate window type
?Findfield("myfieldname")
It will search your database (tables, queries, forms, reports) to find where a particular field name is used.
Documentation and code is here http://allenbrowne.com/ser-73.html