OK. I'm sorry for wasting everyone's time. Like a DUMMY i didn't think simple solution first. The amount of data i am dealing with isn't too large and will actually work better just exporting to an excel file (i'm pretty sure). I would like to thank all that helped (June7, Parfait, and HansUp). The support you guys (everyone on this forum) give has made my job easier by far.
I'm trying to export an Excel Table from my active excel file to an Access database file.
I was getting an error at
"con.excecute sql"
"Run-time error '-2147467259 (80004005)': [Microsoft][ODBC Microsoft Access Driver] Query input must contain at least one table or query."
Sub updateAccess()
Dim con As New ADODB.Connection
Dim connectionString As String
Dim sql, newTable As String
Filename = "C:\Desktop\Quote-Size_Contacts.accdb"
connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" & Filename
con.Open connectionString
' Save current table ("ContactsTbl_Data") to another table ("ContactsTbl_Data_yyyymmdd_hh_mmss")
newTable = "Quote-Size_Contacts_" & Format(Date, "yyyymmdd") & "_" & Format(Now, "hhmmss")
sql = "SELECT CODE, STORE INTO " & newTable & "FROM ContactsTbl_Data"
con.Execute sql
' Delete rows of current table ("ContactsTbl_Data")
sql = "DELETE FROM ContactsTbl_Data"
con.Execute sql
' Insert new rows into current table ("ContactsTbl_Data") from my Excel Sheet
sql = "INSERT INTO ContactsTbl_Data ([CODE], [STORE]) " & _
"SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & ThisWorkbook.FullName & "].[" & ThisWorkbook.Sheets("Sheet2").Name & "$]"
con.Execute sql
con.Close
Set con = Nothing
End Sub
EDIT::
I'm not sure standard protocol for these forums on cleaning up the code and asking more questions so i'll just put an "Edit" here.
I applied the suggestions and matched the fields it was trying to save to my access file. I now get the error: "Method 'Execute' of object '_Connection' failed"
Public Sub updateAccess()
Dim con As New ADODB.Connection
Dim connectionString As String
Dim sql, newTable As String
Filename = "C:\Desktop\Quote-Size_Contacts.accdb"
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & Filename & "'"
con.Open connectionString
' Save current table ("ContactsTbl_Data") to another table ("ContactsTbl_Data_yyyymmdd_hh_mmss")
newTable = "Quote-Size_Contacts_" & Format(Date, "yyyymmdd") & "_" & Format(Now, "hhmmss")
sql = "SELECT Company, Contact, Initials, Position, Address, AddressContd, CityStatePost, MainNo, CellNo, FaxNo, Email INTO [" & newTable & "] FROM ContactsTbl_Data"
con.Execute sql
' Delete rows of current table ("ContactsTbl_Data")
sql = "DELETE FROM ContactsTbl_Data"
con.Execute sql
' Insert new rows into current table ("ContactsTbl_Data") from my Excel Sheet
sql = "INSERT INTO ContactsTbl_Data ([Company], [Contact], [Initials], [Position], [Address], [AddressContd], [CityStatePost], [MainNo], [CellNo], [FaxNo], [Email]) " & _
"SELECT * FROM [Excel 12.0 Xml;HDR=Yes;Database=" & ThisWorkbook.FullName & "].[" & ThisWorkbook.Sheets("Sheet2").Name & "$]"
con.Execute sql
con.Close
Set con = Nothing
End Sub
See if this helps.
Table name has hyphen (-) character so use [ ] characters to delimit. Add a space in front of FROM so text doesn't run together in compiled SQL string.
sql = "SELECT CODE, STORE INTO [" & newTable & "] FROM ContactsTbl_Data"
As for connection to Access database, don't think I've ever used or seen Driver, I use Provider:
connectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source='" & Filename & "'"
Related
I would like to transfer my Excel table directly to MS Access with VBA.
This solution
Using Excel VBA to export data to MS Access table only adds the range of data.
Is it possible to export Excel table to MS Access table directly?
Every time I run this code, it duplicates the data. I can't edit the sCommand into Update statement it gives me an error.
Sub test()
dbWb = Application.ActiveWorkbook.FullName
dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2" 'Data2 is a named range
sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command
dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon
dbCommand.CommandText = sCommand
dbCommand.Execute
dbCon.Close
End Sub
Background: I have a workbook with a lot of tabs that’s brings in data from SQL database (please see example query below). And due to a lot of reasons, I need to create many pivot tables in each tab because each pivot table needs to look at one particular set of data. Every-time I create a pivot table I have to go to “Pivot Table Options” and jot down the pivottable number and then update the VBA code with the appropriate sequential code Set pvt = Me.PivotTables("PivotTable###").
Questions: Is there some VBA code that can reference all the pivot tables within each tab without the need to reference a pivotable number? Cause I have a lot of tabs and I need to create a lot of pivot tables and I’m losing track of the pivotable numbers.
Sub RefreshData()
Dim SQl As String
Dim startDATE As String, endDATE As String
Dim pvt As PivotTable
Set pvt = Me.PivotTables("PivotTable1")
Set pvt = Me.PivotTables("PivotTable2")
Set pvt = Me.PivotTables("PivotTable3")
'pvt.PivotCache.Connection = "ODBC;DSN=" & Application.Range("DSN_Source") & ";DATABASE=" & Application.Range("T123") & ";"
startDATE = Format(Me.Range("SDate"), "yyyy-mm-dd hh:mm:ss")
endDATE = Format(Me.Range("EDate"), "yyyy-mm-dd hh:mm:ss")
SQl = ""
SQl = "WITH ABC As " & vbCrLf
SQl = SQl & "( " & vbCrLf
SQl = SQl & " SELECT Stuff " & vbCrLf
SQl = SQl & ", more stuff, ROW_NUMBER() OVER (PARTITION BY RIGHT(Stuff, 2) " & vbCrLf
SQl = SQl & ", stuff1, stuff2, stuff3 ORDER BY Estuff4 DESC) As RowNum" & vbCrLf
SQl = SQl & " FROM StuffTable " & vbCrLf
SQl = SQl & " WHERE stuff = 'stuffy' AND " & vbCrLf
*snip
With pvt.PivotCache
.CommandType = xlCmdSql
.CommandText = SQl
End With
pvt.RefreshTable
End Sub
You need to loop through all the PivotTables like so:
For Each pvt In Me.PivotTables
With pvt.PivotCache
.CommandType = xlCmdSql
.CommandText = Sql
End With
pvt.RefreshTable
Next
Just to give you background of my work, i have to fetch data from MS Sql on daily basis and for that every time have to go to other server to run the query. Once the query is executed, have to paste into my common drive, which takes a lot time. ~55 mins to paste 5,00,000 row & 30 fields to common or to move file. In total 2 hours for execution & movement from one location to other.
To reduce this i would need your help to use the SQL queries through excel with the below things:
If possible,
Point1: Query will be stored in the text file in the common location
Point2: Query Parameter to be populate to get
Or
Point2:Range to be defined for parameter
If not possible above,
Query will be pasted into the code and parameter to be populated based on the above mentioned suggestion.
Connection type is windows authentication, it will work based on logged in users windows name.
This code will allow you to provide variables that you use within your SQL statement and put those into cells on a spreadsheet (In this case Cred2) and return the results on a separate sheet (Sheet2).
The first portion of the code establishes a connection with the SQL server.
The column Headers will be started in Row 2 and then the data will begin populating starting on row 3. I have used this to pull well over 100,000 records at a time and this works very quickly.
Private Sub CommandButton1_Click()
Dim cn As Object
Dim rs As Object
Dim strCon As String
Dim strSQL As String
strCon = "DRIVER=SQL Server;SERVER=ServerName;DATABASE=DBName;Trusted_Connection=True"
Set cn = CreateObject("ADODB.Connection")
cn.Open strCon
' if not a trusted connection you could replace top line of strCon with
strCon = "DRIVER=SQL Server; Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword"
' set up where you are getting your variables to include in the SQL statement
stat = Sheets("Cred2").Range("c7").Value
barg = Sheets("Cred2").Range("c10").Value
worksite = Sheets("Cred2").Range("c11").Value
' Construct SQL statement
strSQL = "select * " _
& " FROM tableName A , table2 B " _
& "WHERE A.[field1] = B.[field1] " _
& " and field1 like '" & stat & "'" _
& "and field2 like '" & barg & "'" _
& "and field3 like '" & worksite & "'" _
& " order by Field? "
' Build Record Set
Set rs = CreateObject("ADODB.RECORDSET")
rs.ActiveConnection = cn
rs.Open strSQL
' Display Data
For intColIndex = 0 To rs.Fields.Count - 1
Sheet2.Range("A2").Offset(0, intColIndex).Value = rs.Fields(intColIndex).name
Next
Sheet2.Range("A3").CopyFromRecordset rs
' Close Database
rs.Close
cn.Close
Set cn = Nothing
end sub
So I currently have this code
Public Sub DoTrans()
Set cn = CreateObject("ADODB.Connection")
dbPath = Application.ActiveWorkbook.Path & "\db1.accdb"
dbWb = Application.ActiveWorkbook.FullName
dbWs = Application.ActiveSheet.Name
scn = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & dbPath
dsh = "[" & Application.ActiveSheet.Name & "$]" & "namedrange1"
cn.Open scn
ssql = "INSERT INTO Table1 ([fdName], [fdOne], [fdTwo]) "
ssql = ssql & "SELECT * FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
cn.Execute ssql
End Sub
But this inserts into existing Access table. I'd like to be able to modify this to create linked tables, based on a list of named ranges that I have in Excel so that all the named ranges will be converted to tables in Access. Formatting is not an issue as I know the format of the ranges that are named are OK to be used as tables in Access.
Is there a way to easily do this?
INSERT INTO appends to existing tables, SELECT .... INTO creates new ones.
If you want to rewrite that query to a SELECT INTO, it would be as simple as this:
ssql = "SELECT * INTO Table1 "
ssql = ssql & "FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh
Note that you first need to delete the table if you want to overwrite it.
Your question has several subquestions. I can get into creating links in ADO on specific columns, but you haven't shown an attempt, nor have you shared enough information to write an applicable answer.
A sample to elaborate on the TransferSpreadsheet method :
Dim sNT as String, sWB as String, sRN as String sNT = "Table1" sWB = "C:\MyWorkBook.xls" sRN = "namedrange1" DoCmd.TransferSpreadSheet acLink, , sNT, sWB, True, sRN
This has to be run in a module in ms-access.
I'm importing an excel file into access using vba (dao) in the following manner:
Set db = CurrentDb
query = "SELECT DISTINCT * INTO MyTable" _
& " FROM [Excel 12.0 Xml;HDR=Yes;Database=" & filePath & "].[Sheet1$];"
db.Execute (query)
[Sheet1$] is the keyword here. My excel table header starts with line 3. I want to do something like [Sheet1$A3:Lastline].
Is there a simple way to obtain the lastline? Or do I really need to create a VBA Excel Object, open the file and count?
Alternatively, can I change the header start? For instance, by using a custom import scheme instead?
Thanks in advance.
Consider a count query using a recordset and concatenate result in make-table query:
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim query As String
Set db = CurrentDb
Set rst = db.OpenRecordset("SELECT Count(*) AS RowCount" _
& " FROM [Excel 12.0 Xml;HDR=No;Database=" & filePath & "].[Sheet1$]")
query = "SELECT DISTINCT * INTO MyTable" _
& " FROM [Excel 12.0 Xml;HDR=Yes;" _
& " Database=" & filePath & "].[Sheet1$A3:A" & rst!RowCount & "];"
db.Execute (query)
rst.Close
Set rst= Nothing
Set db = Nothing