I'm trying to call part information from SQL to Excel. When a user enters a part number, Excel queries the SQL database and retrieves details about the part (price, description, etc).
I was able to import the data, and use a vlookup to pull in the values, however the import is quite large.
There were some VB scripts out in the webs that would pull data directly from the SQL database into the cells, but those are out of date for Excel 2013.
I'm using the following statement for SQL to pull all the data on the table:
SELECT
PartNum,
PartDescription,
UnitPrice
FROM erp.Part
Ideally would like a script that only asks for a specific part, using WHERE PartNum = part and returns the requested data in a row.
Thanks in advance for any info/help.
your question is vague at best, and you didnt even provide code youve tried. Here is a basic sql from excel vba script
Sub TrackerInput()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = DBEngine.OpenDatabase("pathtoyourfilewhichmightneedotincludecredentialsGoogelitforyourself")
Dim vAr$
vAr = "your input of choice" '.ie part number you were suggesting
Set rs = db.OpenRecordSet("SELECT PartNum, PartDescription, UnitPrice FROM erp.Part WHERE PartNum=" & vAr & ";")
TheLocationWhereYouWantTheDataReturned.CopyFromRecordset rs
End Sub
Your references will need to be set OBV
Solved by handing in my resignation, apparently im too stupid or don't know how to git good enough to do this job anymore. Going to follow my passion and sell umbrellas on the beach.
Related
I have a problem with one project in my work. I have a database on Sharepoint. It's hooked into .accdb file (Access 2007/2010). So far, I used ADODB Connection with standard ConnectionString (only Provider - ACEDB 12.0).
When I try to get data from one of multivalued field from database the recordset is empty for this column. Example:
I have to get few columns: ID, Location, Name, People (MVF), Trainers (MVF).
When single record in People column has MORE than 3-4 values - the recordset for this column is empty. If there's less than 3-4 values i'm getting semicolon-separated values (Even a LEFT JOIN statement to get the source data of MVF doesn't make any difference)
I'm working on Excel - the End-user uses ONLY Excel.
When I watch a Recordset - it has empty values when the people's values should be placed - Basing on this I think the problem is caused by type of connection or something. I've tried also DAO connection - no positive results.
I've also tried to make a temporary database in .accdb file only to execute SQL (INSERT INTO tmpDB SELECT People FROM inputDB; -it's a pseudo-code, the syntax is good) And then I get "Cannot execute INSERT INTO for multivalued field".
I know, that the MVF is not recommended to use, but it's a SharePoint DB, and my role is only to get data from db to Excel.
Update
I tried to use the ODBC driver ...
objConn.ConnectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=" & myconn & ";Uid=Admin;Pwd=;"
... instead of the OLEDB provider ...
objConn.Provider = "Microsoft.ACE.OLEDB.12.0"
objConn.Open myconn
... but now the MVF are always empty.
I resolved this problem. Here's what i've done. The code could have syntax errors. I post here code written from my memory - it's not copy of my working code.
The main and the most important thing is the type of connection. After reserch i found that Microsoft recommends using ADO connection. As I posted earlier, the DAO requires additional looping through recordset and it could be a problem and using DAO with Connection string doesn't look better than ADO.
The best and the only way to get data from MVFs is DAO, but the connection MUST be obtained by "OpenDatabase" method - in this case there's no problems with MVFs with big number of values.
Sub ImportMVFs()
Dim dbs As DAO.Database
Dim rsRecord As DAO.Recordset
Dim rsChild As DAO.Recordset
Dim strSQL As String
Set dbs = "Path to database - works with .accdb too"
Set db = ws.OpenDatabase(dbs) 'This type of connection is a best way to import from MVF.
strSQL = "SELECT * FROM tblToImport;"
Set rsRecord = db.OpenRecordset(strSQL)
Debug.Print rsRecord.Field("Column1").Value
Debug.Print rsRecord.Field("Column2").Value
Do Until rsRecord.EOF
Set rsChild = rsRecord.Field("MultiValuedFieldColumn")
Do Until rsChild.EOF
Debug.Print rsChild.Field(0).Value 'We have to iterate through all mvfs
'Here it's possible to make a temporary table in Access to reorganize MVFs into simple records
'For example: Using SQLQuery as SQL string with Execute method.
db.Execute SQLQuery
rsChild.MoveNext
Loop
rsRecord.MoveNext
Loop
rsRecord.Close
Set rsRecord = Nothing
Set dbs = Nothing
End Sub
I'm building an Excel-based tool that has to be both Windows and Mac compatible. This tool needs to pull data from and push data to a SQL Server. I've written and tested a way to do this that works in Windows and should work in Mac as described here (though that link pertains to Excel 2011):
On Error GoTo err1
Dim connstring As String
Dim sqlstring As String
Dim dArr As Variant
Dim qt As QueryTable
Dim sht As Worksheet
Set sht = ThisWorkbook.Sheets(1)
connstring = "ODBC;DRIVER={SQL Server};SERVER=SERVERNAME;DATABASE=master;Trusted_Connection=yes"
sqlstring = "SELECT 1"
Set qt = sht.QueryTables.Add(Connection:=connstring, Destination:=sht.Range("A1"), Sql:=sqlstring)
With qt
.BackgroundQuery = False
.RowNumbers = False
.Refresh
End With
This approach doesn't work in Excel 2016 for Mac. In fact, when I record the process of adding a connection on a Mac, the QueryTables.Add method doesn't even show a Connection or SQL argument...
Instead of creating the tables programmatically, I thought a workaround could be to manually create the tables and then change the CommandText for the tables programmatically as needed (for different parameters, etc.). But when I try to access the CommandText property of the QueryTable object, the Mac VBEditor tells me that it can't find the member!
Has anyone successfully created ODBC QueryTables programmatically in Excel 2016 for Mac or is this another shortfall of Excel 2016?
I was going crazy trying to find a workaround for this when I came across your question, wishing someone had answered it. I just discovered a work-around today. My problem seems similar to yours so maybe my solution will help you out:
I was unable to use QueryTables.Add or CommandText in VBA, but I was able to create the tables manually and then use data from the excel sheet as a parameter.
I created the ODBC connection manually by clicking New Database Query>From Database, which you probably know how to do. I entered my SQL into the Microsoft Query window as such:
SELECT DISTINCT WIN
FROM RETAIL.OFFER
WHERE WIN LIKE 'XS%'
AND WIN NOT LIKE 'XS92500'
AND WIN NOT LIKE 'XS%a'
AND TITLE = 'The Binge'
I'm new to SQL so it may not be pretty but it worked. However, I needed the title to be a parameter that came from a cell in the spreadsheet instead of having to go in and manually update the SQL each time. I was able to do this by going into Connections>Properties>Definition>Edit Query and changing the SQL to this:
SELECT DISTINCT WIN
FROM RETAIL.OFFER
WHERE WIN LIKE 'XS%'
AND WIN NOT LIKE 'XS92500'
AND WIN NOT LIKE 'XS%a'
AND TITLE = ?
Note: It only worked when I actually pressed the Edit Query button, it changed all the ' to curvy apostrophes if I edited it in the Definition window.
Excel then prompted me to select a parameter to replace the ? in the SQL. You can select a cell in the spreadsheet or enter any other string for the parameter. You can also go back into connections and edit the parameters if needed.
Now, I just use a VBA macro to refresh all connections and pass the data from the cells into the query. This works in my use case, sorry if you already knew about making parameters in this way and you need to use VBA. I couldn't get my VBA to work on my mac either, even though it worked perfectly on my PC. Hopefully this will be helpful to someone out there!
I am currently working on a database for a small Company. They already have a first Version with several tables already implemented. What I would like to do is to create a master table in which data are going to be imported from Excel.
Everytime this table is updated, all the other tables should get updated aswell.
I am not sure how to implement this in Access, so this is whz I am asking for help.
Thanks in advance!
Maurizio
Following sub will import data from excel to access table. Table structure and excel data structure must be same (Column name, data type etc).
Private Sub cmdSpecificSheetOnly_Click()
Dim strExcelPath As String
strExcelPath = "C:\Users\HARUN\Documents\tblEmpInfo.xlsx"
'For Specific Range
'Call DoCmd.TransferSpreadsheet(acImport, acSpreadsheetTypeExcel5, "tblEmpInfo", strExcelPath, True, "Sheet1!A1:E31")
Call DoCmd.TransferSpreadsheet(acImport, acSpreadsheetTypeExcel5, "tblEmpInfo", strExcelPath, True, "Sheet1!")
End Sub
I have three cells in an in Excel 2010 worksheet, say a1, a2, and a3. Every time the user runs my Excel macro, I need it to take the info in those cells and append it to an existing Access DB file. That is all that will be in the db file, just a running list.
So, I don't want to IMPORT from Access. I want this all to happen on the Excel side, preferably without opening access at all. Is this possible or can I just tell my husband to forget about it?
If it IS possible, can someone give me a clue as to how to go about it? Or where to learn about it? I'm ok with VBA in Excel but have zero experience with Access or even with databases.
Thanks!
Create a reference to the Microsoft DAO 3.6 object library and start playing with this code:
Sub DBInsert()
Dim DB As DAO.Database
Dim RS As DAO.Recordset
' open database
Set DB = DAO.OpenDatabase("C:\Users\Myself\Desktop\MyDB.mdb")
' open table as a recordset
Set RS = DB.OpenRecordset("Table1")
' add a record to the recordset
RS.AddNew
' fill fields with data ... in this case from cell A1
RS.Fields("Field1") = [A1]
' write back recordset to database
RS.Update
' important! cleanup
RS.Close
' forget to close the DB will leave the LDB lock file on the disk
DB.Close
Set RS = Nothing
Set DB = Nothing
End Sub
Create a button on the sheet and place this code inside the Button_Click() so the user can send the data to your DB when all entry is done.
Further resources:
Office 2013 / Data Access / How do I ...
Choosing ADO or DAO for Working with Access Databases
I'm debugging some code and need to find out where a
DoCmd.TransferSpreadsheet acImport, , ".....
fails so I've decided to import it 'manually' line-by-line to see where it falls over.
I suppose something like this is what I'm looking for:
mySpreadSheet = ConnectTo(Spreadsheet.xlsx)
while(!mySpreadSheet.EOF)
get(mySpreadSheet.nextLine)
SQL("UPDATE MyTable with mySpreadSheet.nextLine")
I've tried Googling to no avail. Any help is much appreciated!
Additional info:
The column names of the spreadsheet and the Access table are identical.
Every data type is nvarchar(MAX) (Or "Memo" as Access calls it)
The table is a linked table to SQL Server 2008
ADO works well if you have a well defined sheet layout of your data (HansUp answer). If you need added control before loading the objects, you can hook into the excel workbook, and then pull out whatever data you like. It really depends on the level of control you need.
Public Sub LoadExcelToAccess(xlPath As String)
'uses late binding to open excel workbook and open it line by line
'make reference to Microsoft Excel xx.x Object Model to use native functions, requires early binding however
Dim xlApp As Object 'Excel.Application
Dim xlWrk As Object 'Excel.Workbook
Dim xlSheet As Object 'Excel.Worksheet
Dim i As Long
Dim sql As String
Set xlApp = VBA.CreateObject("Excel.Application")
'toggle visibility for debugging
xlApp.Visible = False
Set xlWrk = xlApp.Workbooks.Open(xlPath)
Set xlSheet = xlWrk.Sheets("Sheet1") 'modify to your perticular sheet
'depends on what your trying to do with the sheet
For i = 1 To 10
'quick and dirty: best to load items into custom class collection, then do processing there
sql = "Insert Into [Temp] (Col1) VALUES (" & xlSheet.Cells(i, 1).Value & ")"
DoCmd.RunSQL sql
Next i
'make sure to dispose of objects
xlWrk.Close
xlApp.Quit
Set xlSheet = Nothing
Set xlWrk = Nothing
Set xlApp = Nothing
End Sub
You can create an ADO connection to your spreadsheet (see Connection strings for Excel 2007), then open an ADO recordset with that connection (see StackOverflow: ADODB recordset in VBA says excel field is empty when it's not for example).
Then move through the recordset rows, and create a SQL INSERT statement using the row's values.
strInsert = "INSERT INTO MyTable (first_field, second_field) VALUES ('" & -
rs2.Field(0).Value & "', '" & rs2.Field(1).Value & "');"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailonerror
That code snipped assumes first_field and second_field are text data types. If they are numeric, lose the single quotes.
I think that does roughly what you asked. However, before resorting to code I would check whether the spreadsheet imports cleanly into a new native Access table. (Also, check whether the data types and constraints on that new table are compatible with those of the linked SQL Server table.) If that works, maybe try importing the spreadsheet directly into SQL Server from the Management Studio, or whatever tool is appropriate.
For troubleshooting purposes, try linking to the spreadsheet and see what problems you encounter, including data displaying wrong when you view it in datasheet view.
You can also try just copying your Excel data to the clipboard and pasting it into your Access table. Whatever fails will get written into a 'Paste Errors' table by Access.
Two additional options:
Link the spreadsheet in Access like a table. In Access 2007, go to "external data" pane and select "Import Excel Spreadsheet". You should import to an existing datatable, a new datatable or just link to Excel file. Then, you would work with this new "Excel" table like an Access table (regarded the performance issues, in last case).
Try to fix the Docmd.TransferSpreadsheet problem. I've been using this method for some years, and it works fine, despite it ought to be a little tricky in some cases (I belive its your case). Please, its worthy if you give more information about your problem with this method, including your Access and Excel version.
I hope I've helped. Good luck.