Export Excel Range to Access table VBA - ms-access

I want to have a button on the Excel spreadsheet and have the data copied to the Access table.
The range is an auto-populated field from another sheet in the same workbook.
I tried few codes to make this happen, but I either get an error 1004: application-defined or object-defined error, or no error but data not being copied in Access DB.
My code is copied below.
Sub Export_Data()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim dbPath
Dim x As Long, i As Long
dbPath = "H:\RFD\RequestForData.accdb"
Set cnn = New ADODB.Connection
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
Set rst = New ADODB.Recordset 'assign memory to the recordset
rst.Open Source:="tblRequests", ActiveConnection:=cnn, _
CursorType:=adOpenDynamic, LockType:=adLockOptimistic, _
Options:=adCmdTable
rst.AddNew
For i = 1 To 13
rst(Cells(1, i).Value) = Cells(x, i).Value
Next i
rst.Update
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
MsgBox " The data has been successfully sent to the access database"
Set rst = Nothing
Set cnn = Nothing
End Sub

Looking at your Subroutine I see two things that can make it not to work:
rst(Cells(1, i).Value) = Cells(x, i).Value <- Where is 'x' initialized?
There is only one loop that moves over the fields but I think it should be another loop for the rows in the Excel.
With this two changes, the loop when the records are save could become something like this:
For x = 1 TO lastRow ' Last row has to be calculated somehow
rst.AddNew
For i = 1 To 13
rst(Cells(1, i).Value) = Cells(x, i).Value
Next i
rst.Update
Next x
Hope it helps.

Related

Recordset contents to excel using access vba

I'm trying to write record set contents to excel sheet. My code is not working when trying to move record set contents to Movefirst. My vba code
Set cnn = CurrentProject.Connection
Set rst = New ADODB.Recordset
strSQL = "SELECT * FROM " & qrytable & ""
rst.Open strSQL, cnn, adOpenKeyset, adLockOptimistic, adCmdTableDirect
Set wsSheet1 = wb.Sheets(conSHT_NAME)
wsSheet1.Cells.ClearContents
wsSheet1.Select
For i = 1 To rst.Fields.Count
wsSheet1.Cells(1, i) = rst.Fields(i - 1).Name
Next i
If rst.EOF Then
MsgBox "inside rst"
rst.MoveFirst
wsSheet1.Range("a2").CopyFromRecordset rst
End If
wsSheet1.Columns("A:Q").EntireColumn.AutoFit
rst.Close
The condition If rst.EOF is becomes true and when i'm trying to move record set to rst.Movefirst the debugging control is moving out of the method and moving to the method from where i'm calling this method and not writing contents to excel.
Test for a null recordset with the following:
If (rst.BOF And rst.EOF) Then
rst.Close: set rst = Nothing
Else
rst.MoveFirst
rst.CopyFromRecordset rst
End If

Excel File Locked After Export

I am having some issues with the below piece of code. The data exports fine from access to excel, however, when I go to view the excel file it says its locked for editing. Does anyone know why?
Public Sub ExportFiles()
Dim X As Object
Dim Y As Object
Dim XL As Object
Dim rs As Recordset
Set X = CreateObject("Excel.Application")
Set Y = X.Workbooks.Open("\\POISE\Data\LCS\DomGroup\ICE NMW Performance and DQ\Tasking MI\2014-15\Production Pack Template\OFFICIAL SENSITIVE Tasking Team Production Pack.xlsx")
Set XL = Y.Sheets("Tasking Records")
Set rs = CurrentDb.OpenRecordset("ALL")
XL.Range("A2").CopyFromRecordset rs
Y.SaveAs "\\POISE\Data\LCS\DomGroup\ICE NMW Performance and DQ\Tasking MI\2014-15\Production Pack Output\" & "Tasking " & "Week " & Format(FiscalWeek, "w") & Format(Date, "yyyymmdd") & ".xlsx"
X.Visible = False
Set X = Nothing
Set Y = Nothing
Set XL = Nothing
rs.Close
Set rs = Nothing
End Sub
You're not closing the excel application properly. You need to close the workbook and quit excel before setting the objects to nothing.
For more information see my answer to Remove Excel Task from Task Manager after running vba.
Public Sub ExportFiles()
Dim X As Object
Dim Y As Object
Dim XL As Object
Dim rs As Recordset
Set X = CreateObject("Excel.Application")
Set Y = X.Workbooks.Open("\\POISE\Data\LCS\DomGroup\ICE NMW Performance and DQ\Tasking MI\2014-15\Production Pack Template\OFFICIAL SENSITIVE Tasking Team Production Pack.xlsx")
Set XL = Y.Sheets("Tasking Records")
Set rs = CurrentDb.OpenRecordset("ALL")
XL.Range("A2").CopyFromRecordset rs
Y.SaveAs "\\POISE\Data\LCS\DomGroup\ICE NMW Performance and DQ\Tasking MI\2014-15\Production Pack Output\" & "Tasking " & "Week " & Format(FiscalWeek, "w") & Format(Date, "yyyymmdd") & ".xlsx"
X.Visible = False
' remove objects in reverse order to creation
Set XL = Nothing
' close workbook before quitting excel
Y.Close
Set Y = Nothing
'close excel before setting it to nothing
X.Quit
Set X = Nothing
rs.Close
Set rs = Nothing

Simple code to save an excel workbook from within Access works on one computer but not another?

Ok, I have searched and searched and have not found an answer. I have a very simple code that exports the contents of some tables into an excel workbook and then I want to save the workbook in the same directory as the database. My code works just fine on my computer, but when I try to load the database on a colleague's, the tables export just fine, but the excel workbook will not save as the given name-it just gives a prompt and asks whether you want to save Book1.xlsx If I disable the messages, it just doesn't save it at all. (His curDir is different than mine, but I checked and the workbooks aren't in there either) The database was created in Access 2013 and both computers have Access 2013 installed, although the second one (the one that's not working) also has Access and Excel 2010 installed. The workbook is opening in Excel 2013 though. I tried changing it to an .xls file and specifying the file format number in the saveas command, but that didn't work. I am including the code that works on my computer. I'm sure this is something simple, please help. Oh I should say, it worked fine the first time, but now it won't work (and I deleted the first copy, so I know its not that it doesn't want to overwrite) I'm pulling my hair out!
Public Function DeleteExcessPendragonRecords()
On Error GoTo DeleteExcessPendragonRecords_err
Dim strSQL1 As String
Dim strSQL2 As String
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim oXL As Excel.Application
Dim oWB As Excel.Workbook
Dim osheet As Excel.Worksheet
Dim strSQLlinkedtables As String
Dim rs3 As DAO.Recordset
Dim currdirpath As String
currdirpath = CurDir()
'Exporting all tables into Excel Spreadsheet
Set db = CurrentDb
DoCmd.Hourglass True
Call RefreshSharePointLinks
strSQLlinkedtables = "SELECT tbl_PendragonTableNames.LocalLink FROM tbl_PendragonTableNames WHERE tbl_PendragonTableNames.ID < 15"
Set rs1 = db.OpenRecordset(strSQLlinkedtables)
Set oXL = CreateObject("Excel.Application")
oXL.Visible = True
Set oWB = oXL.Workbooks.Add
On Error Resume Next
Do Until rs1.EOF
oWB.Sheets.Add
Set osheet = oWB.ActiveSheet
osheet.Name = rs1.Fields(0)
On Error Resume Next
Dim Linkedtable As String
Linkedtable = rs1.Fields(0)
Set rs2 = db.OpenRecordset(Linkedtable)
For i = 0 To rs2.Fields.Count - 1
osheet.Cells(1, i + 1).value = rs2.Fields(i).Name
Next i
osheet.Range("A2").CopyFromRecordset rs2
rs1.MoveNext
Loop
oWB.SaveAs currdirpath & "\PendragonBackup_" & Format(Date, "yyyymmdd") & ".xlsx"
rs2.Close
rs1.Close
oWB.Close
oXL.Close
oXL.Quit
db.Close
Set oWB = Nothing
Set oXL = Nothing
Set rs2 = Nothing
Set rs1 = Nothing
Set db = Nothing
'Code continues after this, but this is the relevant part
Instead of
currdirpath = CurDir()
try:
currdirpath = CurrentProject.Path

Transferring using ADO 5 worksheets into 5 tables

I have been struggling to transfer data from multiple excel worksheets into multiple access tables. So how this goes is this way. I have 5 worksheets and each of this worksheet is to be transferred from Excel into a specific Access table. How do I do this using VBA?
I cant seem to put the file in so I hope you guys understand!
Thanks in advance for helping me!!
You can use ADO. First, set a reference to the ADO library in the VBE: Tools, References. Look for Microsoft ActiveX Date Objects Library 6.1 (or 6.0) and tick the box next to it.
Then you can use the code below to post data from a sheet to a table in the Access database (use this in a loop if you want to do multiple sheets):
Dim i As Long, j As Long
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim arr() As Variant
'Load the data from a sheet into an array
arr = Sheets(1).Range("A2:B10").Value
'Connect to Access database
Set cn = New ADODB.Connection
With cn
.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Documents\Database1.accdb"
.Open
End With
'Post data to table
Set rs = New ADODB.Recordset
With rs
.Source = "Table1"
.ActiveConnection = cn
.CursorType = adOpenStatic
.CursorLocation = adUseServer
.LockType = adLockOptimistic
.Open
For i = 1 To UBound(arr, 1)
.AddNew
For j = 1 To UBound(arr, 2)
.Fields(j).Value = arr(i, j) 'This assumes you have an autonumber ID field. (Field indexes in recordsets are 0 based.)
Next
.Update
Next
.Close
End With
'Clean up
Set rs = Nothing
cn.Close
Set cn = Nothing
EDIT:
If you want to check if a record already exists in the table, use the recordset FILTER property. Say you have an "ID" in column 1 of your spreadsheet and an "ID" field in your database table, then do:
rs.Filter = "ID='" & arr(1,j) & "'"
If rs.RecordCount > 0 then
'Record(s) already exist
...

VBA Code for Dynamic VLookup Between Two Open Spreadsheets from MS Access 2010

I've taken a different approach to a work project and I'm running into a wall. I've Google'd everything that I can think to Google and searched multiple forums before coming back to S.O. to ask for more help. I have a form in Access that let's users enter a customer/division combination, checks to make sure that there is an existing file path for that customer, then opens excel template files and saves them to the correct folder with a customer specific file name. This all seems to be working fine. Here's the part that has me completely stumped. The next part of this would be to open two of the excel files assigning, the Workbooks as variables xlWB1 and xlWB2 and the Worksheets as xlWS1 and xlWS2(Sheet1). I need to start in xlWB1.xlWS1.(cell D2) and do a VLookup on the value (item number) of that cell against the values of the cells in the range xlWB2.xlWS2.Range(D2:D1937). My hope was to count the total number of rows in each worksheet before starting the VLookup so that I could assign that value to a variable and use that variable to define the bottom of the range. I'm going to apologize in advance if the answer to this is something simple. I've never tried to perform any operations in Excel from Access using VBA, so I'm also struggling with the syntax. Please let me know if my question isn't clear or if there is any additional information that you need. I've pasted my starting code below.
UPDATED CODE IN CASE ANYONE ELSE NEEDS TO USE IT! THANK YOU ALL FOR THE HELP!!
Sub modExcel_SixMonth()
Const WB_PATH As String = "\\FMI-FS\Users\sharp-c\Desktop\TestDir\"
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Dim xlRng As Excel.Range
Dim rCount As Long
Dim xlWB2 As Excel.Workbook
Dim xlWS2 As Excel.Worksheet
Dim rCount2 As Long
Dim sFormula As String
Dim i As Long
Dim xlSheetName As String
Dim bolIsExcelRunning As Boolean
On Error Resume Next
Set xlApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
Set xlApp = CreateObject("Excel.Application")
Else
bolIsExcelRunning = True
End If
xlApp.Visible = False
Set xlWB = xlApp.Workbooks.Open(WB_PATH & "acct 900860 Kentucky RSTS.xlsx")
Set xlWS = xlWB.Sheets(1)
Set xlWB2 = xlApp.Workbooks.Open(WB_PATH & "acct 900860 six months.xlsx")
Set xlWS2 = xlWB2.Sheets(1)
xlSheetName = xlWS2.Name
' rCount: RSTS Row Count
rCount = xlWS.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
Debug.Print "rCount : " & rCount
' rCount2: 6 Months Row Count
rCount2 = xlWS2.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count
Debug.Print "rCount2 : " & rCount2
xlWS.Activate
With xlWS
For i = 2 To rCount
sFormula = "=VLOOKUP(C" & i & ", '" & WB_PATH & "[" & "acct 900860 six months.xlsx" & "]" & _
xlSheetName & "'!$D$2:$D$" & rCount2 & ", 1, 0)"
Debug.Print sFormula
.Range("D" & i).Formula = sFormula
DoEvents
Next
End With
xlWB.Save
xlWB2.Close False 'Closes WB Without Saving Changes
Set xlWB2 = Nothing
Set xlWS = Nothing
xlWB.Close
Set xlWB = Nothing
If Not bolIsExcelRunning Then
xlApp.Quit
End If
Set xlApp = Nothing
End Sub
I think this is maybe closer to what you need. Only need a single instance of excel for both workbooks...
Sub modExcel_SixMonth()
Const WB_PATH As String = "C:\Documents and Settings\Chris\Desktop\TestDir\"
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Dim xlRng As Excel.Range
Dim rCount As Long
Dim xlWB2 As Excel.Workbook
Dim xlWS2 As Excel.Worksheet
Dim xlRng2 As Excel.Range
Dim rCount2 As Long
Dim sFormula As String
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWB = xlApp.Workbooks.Open(WB_PATH & "acct 900860 Kentucky RSTS.xlsx")
Set xlWS = xlWB.Sheets(1)
Set xlWB2 = xlApp.Workbooks.Open(WB_PATH & "acct 900860 six months.xlsx")
Set xlWS2 = xlWB2.Sheets(1)
' rCount: RSTS Row Count
rCount = xlWS.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count - 1
Debug.Print "rCount : " & rCount
' rCount2: 6 Months Row Count
rCount2 = xlWS2.Range("A:A").Cells.SpecialCells(xlCellTypeConstants).Count - 1
Debug.Print "rCount2 : " & rCount2
sFormula = "=VLOOKUP(C2," & xlWS2.Range("D2:D1937").Address(True, True, , True) & _
",1,FALSE)"
Debug.Print sFormula
With xlWS
.Range("D2").Formula = sFormula
End With
End Sub
Have you tried using the same application object? I believe this was a comment on this question earlier.
Additionally, if this doesn't work, you could use the find method of the range object. I.e.
XLWB2.Range("Your range here").find(XLWB1.Range( _
"Cell containing value you're looking for").Value,lookat:=xlwhole)