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
Related
I am trying to retrieve records from a table in access using VBA. So far I have this simple function:
Private Function GNCN() As String
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim cm As ADODB.Command
Dim strSQL As String
Dim intYD As Integer
Set cn = CurrentProject.Connection
'cn.CursorLocation = adUseClient
rs.CursorLocation = adUseClient
rs.LockType = adLockReadOnly
intYD = 16
strSQL = "SELECT DCN FROM tblDCD WHERE (DCN like '" & intYD & "*')"
Set rs = cn.Execute(strSQL)
Debug.Print rs.RecordCount
Set rs = Nothing
Set cm = Nothing
Set cn = Nothing
End Function
When I run this, I don't get any records returned.
However if I take the SQL query:
SELECT DCN FROM tblDCD WHERE (DCN like '16*')
and run this within Access' query builder, I get around 912 records returned, so I know I am able to retrieve the records and that the query itself appears to be correct.
The table is simple data which consists of string values such as (in the DCN column):
"13000"
"17001"
"16003"
Around 38000 in total so I shaln't print them all here...
Does anyone know why this will work via the query builder but not via VBA?
Thanks
Appear to be mixing DAO and ADODB. Consider:
Private Function GNCN() As String
Dim rs As DAO.Recordset
Dim strSQL As String
Dim intYD As Integer
intYD = 13
strSQL = "SELECT DCN FROM Rates WHERE DCN like '" & intYD & "*';"
Set rs = CurrentDb.OpenRecordset(strSQL)
rs.MoveLast
Debug.Print rs.RecordCount
Set rs = Nothing
End Function
I'm trying to write This Programm:
Function funktion()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim rt As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("All")
Do While Not rs.EOF
Set rk = db.OpenRecordset("Archive")
'here I want to copy(append) the current index(of Table"All") into the next free
index (of table "archive")
Do something
rs.MoveNext
Loop
my programm works well just I need to append the current row from "All" into the next free row from table "Archive".
Thank you for your help
here´s a example of how you can do this using ADO and not DAO to access data.... in example above.. i add all records to another table... but easily you can just add the current record in your loop...
Dim cnn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim rs2 As ADODB.Recordset
Set cnn = CurrentProject.Connection
Set rs = New ADODB.Recordset
Set rs2 = New ADODB.Recordset
'open main recordset (TDetPed)
rs.Open "SELECT TDetPed.* FROM TDetPed WHERE CodPed = " & CodPed & "", cnn, adOpenKeyset, adLockOptimistic
'open clone table recordset (TDetPedTemp)
rs2.Open "TDetPedTemp", cnn, adOpenKeyset, adLockOptimistic
'move to first record of main table
rs.MoveFirst
'add record by record in clone table(rs2) from maintable(rs)
Do Until rs.EOF
rs2.AddNew
rs2("CodPed") = rs("CodPed")
rs2("CodDetPed") = rs("CodDetPed")
rs2("CodInterno") = rs("CodInterno")
rs2("DescrDetPed") = rs("DescrDetPed")
rs2("DescontoDetPed") = rs("DescontoDetPed")
rs2("CodProd") = rs("CodProd")
rs2("PreçoDetPed") = rs("PreçoDetPed")
rs2("QtdeDetPed") = rs("QtdeDetPed")
'update current added record in clone table
rs2.Update
'move to next record in main table
rs.MoveNext
'Move para o proximo registro do detalhe do pedido
Loop
'close everthing
rs.Close
rs2.Close
cnn.Close
'clean everthing
Set rs = Nothing
Set rs2 = Nothing
Set cnn = Nothing
Just completing the answer... a simple example using DAO (Data Access Objetcs) and not ADO(Active Data Objetcs). (more info https://msdn.microsoft.com/en-us/library/aa261340%28v=vs.60%29.aspx / http://www.utteraccess.com/wiki/index.php/Choosing_between_DAO_and_ADO)
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = dbsNorthwind.OpenRecordset("Tbl1")
rs.AddNew
rs!Cidade = "Curitiba"
rs!Country = "Brazil"
'.... others fields
rs.Update
I have a continuous form with a command button in the footer that updates the current record with a value that will make the record no longer show in the form once requeried. I want the user to be able to click the button and once the record is updated, move to the next record, not the first as is the default behaviour. I have code that I would think should work but doesn't, it keeps going back to the first record on the form.
Private Sub cmdCloseReq_Click()
Dim ReqID As String
ReqID = Me.txtReqID
Dim rst As Recordset
Dim strBookmark As Integer
Set rst = Me.RecordsetClone
rst.MoveNext
If Not rst.EOF Then ' if not end-of-file
strBookmark = rst.Bookmark ' ...save the next record's bookmark
Dim cmd As New ADODB.Command
With cmd
.ActiveConnection = CurrentProject.Connection
.CommandType = adCmdStoredProc
.CommandText = "spUpdateLOG_ReqCompleteDate"
.Parameters("#ReqID") = ReqID
.Execute
End With
Me.Requery
Me.Bookmark = strBookmark
End If
Set rst = Nothing
End Sub
OK, I found a solution based on rene's post. I grab the next records primary key, do an update then after the requesry I find the next record and set the bookmark to that. Here is the code:
Private Sub cmdCloseReq_Click()
Dim ReqID As String
ReqID = Me.txtReqID
Dim rst As New ADODB.Recordset
Dim strBookmark As String
Set rst = Me.RecordsetClone
With rst
.Find "[ReqID] = '" & ReqID & "'"
.MoveNext
strBookmark = rst.Fields(0)
End With
If Not rst.EOF Then ' if not end-of-file
' ...save the next record's bookmark
Dim cmd As New ADODB.Command
With cmd
.ActiveConnection = CurrentProject.Connection
.CommandType = adCmdStoredProc
.CommandText = "spUpdateLOG_ReqCompleteDate"
.Parameters("#ReqID") = ReqID
.Execute
End With ' ...delete the record
Me.Requery
Set rst = Me.RecordsetClone
With rst
.Find "[reqID]= " & strBookmark
Me.Bookmark = .Bookmark
End With
Else
With cmd
.ActiveConnection = CurrentProject.Connection
.CommandType = adCmdStoredProc
.CommandText = "spUpdateLOG_ReqCompleteDate"
.Parameters("#ReqID") = ReqID
.Execute
End With ' ...delete the record
Me.Requery
End If
Set rst = Nothing
I recall that Bookmarks are invalidated after a Requery. If you have a primary key you can better grab that one and after requery move the current record to the previously obtained primary key
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
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