Accessing Field Value in Recordset -- Access VBA - ms-access

Here's what I'm trying to do and I apologize if I'm headed the wrong direction. I'm trying to cycle through the filepath's stored in table t_Directory and if the file extension is "xlsx" open the Excel file and update another table called t_SheetInfo with the FileID of the Excel Worksheet and sheet count and the sheet name. Would anyone have a minute to check what I've got so far or steer me in the right direction if there's a more efficient way to do it? I'm not 100% sure that I know what I'm doing. As always, thank you in advance for any help!!
Dim db As DAO.Database
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Dim xlWS As Excel.Worksheet
Private Sub CycleThroughWorkSheets()
Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim sSQL1 As String
Dim sSQL2 As String
Dim sSQL3 As String
Dim rsFilePath As String
Dim rsWSName As String
Set db = CurrentDB
sSQL1 = "SELECT t_Directory.FileID, t_Directory.FilePath FROM t_Directory " & _
"WHERE (((t_Directory.FileExtension)=""'xlsx'""))"
Set rs = db.OpenRecordset("sSQL1", dbOpenDynaset)
With rs
rs.MoveFirst
Do While Not rs.EOF
rsFilePath = rs.Fields("[FilePath]")
OpenWorkBook (rsFilePath)
Set rs2 = db.OpenRecordset("t_SheetInfo", dbOpenDynaset)
With rs2
rs2.MoveFirst
Do While Not rs2.EOF
rs2.AddNew
rs2.Fields("FileID") = rs.Fields(1)
rs2.Fields("[SheetIndex]") = WorkSheetCount(rsFilePath)
rs2.Fields("[SheetName]") = WorkSheetName(WorkSheetCount)
rs2.Update
Next
Loop
End With
End With
Set rs = Nothing
Set rs2 = Nothing
End Sub
Public Function WorkSheetCount(rsFilePath As String) As Integer
Set xlWB = xlApp.Workbooks.Open(rsFilePath)
WorkSheetCount = xlWB.Sheets.Count(rsFilePath)
Debug.Print "WorkSheetCount : " & WorkSheetCount
End Function
Public Function WorkSheetName(WorkSheetCount As Integer) As String
Set xlWB = xlApp.Workbooks.Open(rsFilePath)
WorkSheetName = Worksheets(WorkSheetCount).Name
Debug.Print "WorkSheetName : " & WorkSheetName
End Function

Try something on these lines. Step through.
Dim xlApp As New Excel.Application
Dim xlWB As Excel.Workbook
Dim sh As Object ''Some sheets may be charts
Dim rs As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim sSQL1 As String
Dim sSQL2 As String
Dim sSQL3 As String
Dim rsFilePath As String
Dim rsWSName As String
Set db = CurrentDb
xlApp.Visible = True
sSQL1 = "SELECT t_Directory.FileID, t_Directory.FilePath FROM t_Directory " & _
"WHERE t_Directory.FileExtension='.xlsx'"
Set rs2 = db.OpenRecordset("t_SheetInfo", dbOpenDynaset)
Set rs = db.OpenRecordset(sSQL1, dbOpenDynaset)
Do While Not rs.EOF
rsFilePath = rs.Fields("[FilePath]")
Set xlWB = xlApp.Workbooks.Open(rsFilePath)
For Each sh In xlWB.Sheets
rs2.AddNew
rs2.Fields("FileID") = rs.Fields("FileID")
rs2.Fields("[SheetIndex]") = sh.Index
rs2.Fields("[SheetName]") = sh.Name
rs2.Update
Next
rs.MoveNext
xlWB.Close False
Loop
Set rs = Nothing
Set rs2 = Nothing
xlApp.Quit

Related

Sending notification email based on query results

I have a query table which shows the "FirstName", "LastName", "DueDate". What I wanted to do is create a follow-up process. If the duedate is today (date()), access needs to send notification email to the one general email address.
My code works only for first record in the query, it doesn't goes to other records.
Here is the code that I am using for;
Public Sub FollowUpEmail()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim oApp As Object
Dim oEmail As Object
Set oApp = CreateObject("Outlook.Application")
Set oEmail = oApp.CreateItem(0)
Set db = CurrentDb
strSQL = "SELECT FirstName, SurName, DueDate" & _
" FROM TestQuery"
Set rs = db.OpenRecordset(strSQL, dbOpenDynaset)
While Not rs.EOF
SendKeys "^{ENTER}"
With oEmail
.To = "xxx"
.Subject = rs.Fields("FirstName").Value & "/" & "Deadline"
.Body = "test"
.Display
End With
rs.MoveNext
Wend
rs.Close
Set rs = Nothing
Set db = Nothing
Set oApp = Nothing
Set oEmail = Nothing
End Sub
You will need to create & send a new email for every iteration of the loop, for example:
Public Sub FollowUpEmail()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim oApp As Object
Set oApp = CreateObject("Outlook.Application")
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT FirstName, SurName, DueDate FROM TestQuery")
Do Until rs.EOF
With oApp.CreateItem(0)
.To = "xxx"
.Subject = rs!FirstName & "/" & "Deadline"
.Body = "test"
.Display
End With
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
Set db = Nothing
Set oApp = Nothing
End Sub
Or, if you want to send the emails directly:
Public Sub FollowUpEmail()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim oApp As Object
Set oApp = CreateObject("Outlook.Application")
Set db = CurrentDb
Set rs = db.OpenRecordset("SELECT FirstName, SurName, DueDate FROM TestQuery")
Do Until rs.EOF
With oApp.CreateItem(0)
.To = "xxx"
.Subject = rs!FirstName & "/" & "Deadline"
.Body = "test"
.Send
End With
rs.MoveNext
Loop
rs.Close
Set rs = Nothing
Set db = Nothing
Set oApp = Nothing
End Sub

In Access VBA, how do I copy fields which consist of Attachments from single record to another table?

I tried using SQL but with no success. I then tried DAO, the other fields
seems to work but the column which holds attachments fails. Has someone done this before?
Private Sub copyfromtblA_Click()
Dim db As Database
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim rs3 As DAO.Recordset2
'Set db = CurrentDb()
Set rs1 = db.OpenRecordset("tblA")
Set rs2 = db.OpenRecordset("tblB")
With rs2
rs2.AddNew
rs2.Fields("ItemNo").Value = Me.ItemNo.Value
rs2.Fields("Quantity").Value = Me.Quantity.Value
rs2.Fields("itemName").Value = Me.itemName.Value
'This is were I get the error since this field contains images as attachments
rs2.Fields("ItemImage").Value = Me.itemImage.Value
rs2.Update
rs1.MoveNext
End With
rs2.Close
Form.Requery
Set rs2 = Nothing
rs1.Close
Set rs1 = Nothing
End Sub
Something like this:
Private Sub copyfromtblA_Click()
Dim db As Database
Dim rs1 As DAO.Recordset
Dim rs2 As DAO.Recordset
Dim rsAtt1 As DAO.Recordset2
Dim rsAtt2 As DAO.Recordset2
Set db = CurrentDb()
Set rs2 = db.OpenRecordset("tblB")
With Me.Recordset
rs2.AddNew
rs2.Fields("ItemNo").Value = !ItemNo.Value
rs2.Fields("Quantity").Value = !Quantity.Value
rs2.Fields("itemName").Value = !itemName.Value
Set rsAtt1 = !ItemImage.Value
Set rsAtt2 = rs2!ItemImage.Value
With rsAtt1
Do While Not .EOF
rsAtt2.AddNew
rsAtt2.Fields("FileData") = .Fields("FileData")
rsAtt2.Fields("FileName") = .Fields("FileName")
rsAtt2.Update
.MoveNext
Loop
End With
rs2.Update
End With
rs2.Close
Set rs2 = Nothing
rsAtt1.Close
Set rsAtt1 = Nothing
'I was getting an error here! removing the "rsAtt2.Close" solved the problem
'rsAtt2.Close
Set rsAtt2 = Nothing
End Sub

VBA docmd.Transferspreadsheet Loop fails (with no error) on 3rd and 4th loop only, then resumes to work

--- This code should loop through a recordset created with unique records (sub_nbr) from a tbl_ccg_all_sub. During the loop, it exports the data associated with a given sub_nbr to an excel template already saved (Select * where loop#=sub_nbr). It will work until the 3rd loop, where it stupidly transfers the same data from the previous loop into the spreadsheet. It then resumes working on the 5th or 6th loop. Craziness!!!
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim v As String
Dim objfso As Object
Set objfso = CreateObject("scripting.filesystemobject")
Set db = CurrentDb()
Set rs1 = db.OpenRecordset("select distinct sub_nbr from tbl_ccg_all_sub")
Dim strqry As String
Dim qdftemp As DAO.QueryDef
Dim strQdf As String
strQdf = "_TempQuery_"
Do While Not rs1.EOF
v = rs1.Fields(0).Value
strqry = "select * from tbl_ccg_all_sub where sub_nbr = '" & v & "'"
Set qdftemp = CurrentDb.CreateQueryDef(strQdf, strqry)
qdftemp.Close
Set qdftemp = Nothing
Dim filename As String
filename = "C:\Users\U557687\Desktop\test_db\test_template.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, strQdf, filename, True
DoEvents
objfso.copyfile filename, "C:\Users\U557687\Desktop\Test_db\" & v & ".xlsx"
CurrentDb.QueryDefs.Delete strQdf
rs1.MoveNext
Loop
rs1.Close
''''' This example creates an index of unique values in a dataset. It then loops through the index, exports to .xls template file (already saved somewhere), and saves a copy of the template using the distinct value. I use this to create a separate file for each client I have. One tab in my sheet contains formulas linked to the tab that will be updated by each client's data. Bam. You're welcome.
Dim db As DAO.Database
Dim rs1 As DAO.Recordset
Dim v As String
Dim objfso As Object
Set objfso = CreateObject("scripting.filesystemobject")
Set db = CurrentDb()
Set rs1 = db.OpenRecordset("select distinct sub_nbr from tbl_ccg_all_sub")
Dim strqry As String
Dim qdftemp As DAO.QueryDef
Dim strQdf As String
Do While Not rs1.EOF
Dim xlApp As Excel.Application
Dim xlWB As Excel.Workbook
Set xlApp = New Excel.Application
With xlApp
.Visible = False ''''REMINDER: CHANGE THIS TO FALSE WHEN CODING COMPLETE
Set xlWB = .Workbooks.Open("C:\Users\poop\Desktop\test_db\test_template.xlsx", , False)
.Sheets("_tempquery_").Cells.ClearContents ''''FORMATTING MAINTAINED, ONLY CONTENTS ARE CLEARED
xlWB.Close True
End With
'''Workbooks("C:\Users\poop\Desktop\test_db\test_template.xlsx").Close True
''Stop
strQdf = "_TempQuery_"
v = rs1.Fields(0).Value
strqry = "select * from tbl_ccg_all_sub where sub_nbr = '" & v & "'"
Set qdftemp = CurrentDb.CreateQueryDef(strQdf, strqry)
qdftemp.Close
Set qdftemp = Nothing
Dim filename As String
filename = "C:\Users\poop\Desktop\test_db\test_template.xlsx"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12, strQdf, filename, True
DoEvents
CurrentDb.QueryDefs.Delete strQdf
''''Stop
objfso.copyfile filename, "C:\Users\poop\Desktop\Test_db\" & v & ".xlsx"
''''Stop
rs1.MoveNext
Loop
rs1.Close

Access Recordset in Multiple Textboxes using ADO

I am trying to fill my 31 textboxes with one single recordset containing 31 days (from Jan 1st to Jan 31st).
While it's clear for me how to assign each field of the query to the relevant textbox, it's not clear at all how to assign the several values contained in one single field of the query to multiple textboxes.
As for example, this is my starting code:
Private Sub FillDates()
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Set cnn = CurrentProject.Connection
Set rst = New ADODB.Recordset
ssql = "SELECT PricingDate From RoomCalendar WHERE PricingDate BETWEEN #01/01/2016# AND #31/01/2016# AND RateRoomCombinationId=17"
rst.Open ssql, cnn
Do Until rst.EOF = True
'txt1.Value = rst.Fields!PricingDate
'txt2.Value = rst.Fields!PricingDate
'txt3.Value = rst.Fields!PricingDate
rst.MoveNext
Loop
End Sub
Thank you in advance for your help
You can use:
Dim cnn As ADODB.Connection
Dim rst As ADODB.Recordset
Dim Record As Integer
Dim Records As Integer
Set cnn = CurrentProject.Connection
Set rst = New ADODB.Recordset
ssql = "SELECT PricingDate From RoomCalendar WHERE PricingDate BETWEEN #2016/01/01# AND #2016/01/31# AND RateRoomCombinationId=17"
rst.Open ssql, CNN
rst.MoveLast
rst.MoveFirst
Records = rst.RecordCount
For Record = 1 To Records
Me("txt" & CStr(Record)).Value = rst.Fields!PricingDate.Value
rst.MoveNext
Next
End Sub
Note please, the format for the date expressions.
I managed to solve the question on my own. Final code is:
Private Function FillDates()
Dim cnn As ADODB.Connection
Dim ssql As String
Dim rst As ADODB.Recordset
Set cnn = CurrentProject.Connection
Dim i As Integer
Dim Records As Integer
ssql = "SELECT PricingDate From RoomCalendar WHERE PricingDate BETWEEN #2016/01/01# AND #2016/01/31# AND RateRoomCombinationId=17"
Set rst = New ADODB.Recordset
rst.CursorLocation = adUseClient
rst.Open ssql, cnn
Records = rst.RecordCount
For i = 1 To Records
Me("Text" & i).Value = rst.Fields!PricingDate.Value
rst.MoveNext
Next i
'' Clean up
rst.Close
Set rst = Nothing
End Function
Thanks for your help

Display Recordset in New Form

The following code takes a parameter from a form and passes it to a stored procedure in vba. I am returning the values correctly and the stored procedure works when using debug.Print. Now I need to display the results of the stored procedure in the form "cat_percent_match". All this happens when the button is clicked. The code below does open the form, but now I need to pass the record set to it and display the results.
Any help is greatly appreciated.
Dim Cmd1 As ADODB.Command
Dim lngRecordsAffected As Long
Dim rs1 As ADODB.Recordset
Dim intRecordCount As Integer
'-----
Dim cnnTemp As ADODB.Connection
Set cnnTemp = New ADODB.Connection
cnnTemp.ConnectionString = "DRIVER=SQL Server;SERVER=***;" & _
"Trusted_Connection=No;UID=***;PWD=***;" & _
"Initial Catalog=IKB_QA;"
cnnTemp.ConnectionTimeout = 400
'Open Connection
cnnTemp.Open
Set Cmd1 = New ADODB.Command
Cmd1.ActiveConnection = cnnTemp
'---
With Cmd1
Dim localv As Integer
Dim inputv
localv = [Forms]![Start]![Selection]![cat_code]
.CommandText = "dbo.ix_spc_planogram_match_cat_percent " & inputv
.CommandType = adCmdStoredProc
Set inputv = Cmd1.CreateParameter("#deptcode", 3, 1, 10000, localv)
Cmd1.Parameters.Append inputv
Set rs1 = Nothing
Set rs1 = Cmd1.Execute
DoCmd.OpenForm "Cat_Percent_Match"
End With
End Sub
The relevant article is http://support.microsoft.com/kb/281998
Private Sub Form_Open(Cancel As Integer)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
'Use the ADO connection that Access uses
Set cn = CurrentProject.AccessConnection
'Create an instance of the ADO Recordset class, and
'set its properties
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
.Source = "SELECT * FROM Customers"
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
'Set the form's Recordset property to the ADO recordset
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End Sub
So in this particular case, you can try:
DoCmd.OpenForm "Cat_Percent_Match"
Set Forms.Cat_Percent_Match.Recordset = rs1