I have been using below functions and i am trying to add one condition in the below function that is if Col"1" strings are not matched with Category strings then there are strings with the name of "Permanent" in the Col"1" so the function will go for the "Permanent" along with the Condition.
But now i have been receiving an compile error on the first line Set Result = RSToHtmlValues(Query.RS)
i do not know why the error is come any help will be appreciated.
'Return an HTMLValues object for matching record, else return Nothing
Private Function GetHtmlValues(Category As String, Permanent As String, Condition As String) As Htmlvalues
Dim Result As Htmlvalues
Dim TblHtmlValues As ListObject
Dim TableAddress As String
Dim strQuery As String
Dim Query As WbkQuery
TableAddress = ThisWorkbook.Sheets("Sheet1").ListObjects("Table4").Range.Address
TableAddress = Replace(TableAddress, "$", "")
Set Query = New WbkQuery
'Try the first query...
Query.ExecuteSql CategoryConditionSql(TableAddress, Category, Condition)
Set Result = RSToHtmlValues(Query.RS)
'If no result from first query then run the second using `Permanent`
If Result Is Nothing Then
Query.ExecuteSql CategoryConditionSql(TableAddress, Permanent, Condition)
Set Result = RSToHtmlValues(Query.RS)
End If
GetHtmlValues = Result
End Function
'Construct SQL for Category/Condition query
Function CategoryConditionSql(TableAddress As String, Category As String, Condition As String)
Dim strQuery As String
strQuery = "SELECT * FROM [" & LISTS_SHEET_NAME & "$" & TableAddress & "]" & _
" WHERE Category = '" & Category & "'" & _
" AND Condition = '" & Condition & "'"
End Function
'Return HTMLvalues object from RS (or nothing if RS has no records)
Function RSToHtmlValues(RS As Object) As Htmlvalues
Dim Result As Htmlvalues
If Not RS.EOF Then
Set Result = New Htmlvalues
Result.ConditionDescription = RecordsetHelpers.FieldToString(Query.RS.Fields("Condition Description"))
Result.Description1 = RecordsetHelpers.FieldToString(Query.RS.Fields("Description 1"))
Result.Description2 = RecordsetHelpers.FieldToString(Query.RS.Fields("Description 2"))
End If
Set RSToHtmlValues = Result
End Function
Since the RSToHtmlValues() function accepts only the RS property, you should access only this object, not the Query.
Just remove the Query qualifier:
'...
If Not RS.EOF Then
Set Result = New Htmlvalues
Result.ConditionDescription = RecordsetHelpers.FieldToString(RS.Fields("Condition Description"))
Result.Description1 = RecordsetHelpers.FieldToString(RS.Fields("Description 1"))
Result.Description2 = RecordsetHelpers.FieldToString(RS.Fields("Description 2"))
End If
'...
Update:
As discussed in the comments, HtmlValues is not an object. Trying to Set the reference as well as check for Nothing will generate errors.
Try the below. I had to change the RSToHtmlValues() function in order to be able to replace the statement:
If Result Is Nothing Then
Hope I didnt miss anything.
'Return an HTMLValues object for matching record, else return Nothing
Private Function GetHtmlValues(Category As String, Permanent As String, Condition As String) As HtmlValues
Dim Result As HtmlValues
Dim TblHtmlValues As ListObject
Dim TableAddress As String
Dim strQuery As String
Dim Query As WbkQuery
TableAddress = ThisWorkbook.Sheets("Sheet1").ListObjects("Table4").Range.Address
TableAddress = Replace(TableAddress, "$", "")
Set Query = New WbkQuery
'Try the first query...
Query.ExecuteSql CategoryConditionSql(TableAddress, Category, Condition)
'If no result from first query then run the second using `Permanent`
If Not TryRSToHtmlValues(Query.RS, Result) Then
Query.ExecuteSql CategoryConditionSql(TableAddress, Permanent, Condition)
TryRSToHtmlValues Query.RS, Result
End If
GetHtmlValues = Result
End Function
'Construct SQL for Category/Condition query
Function CategoryConditionSql(TableAddress As String, Category As String, Condition As String)
Dim strQuery As String
strQuery = "SELECT * FROM [" & LISTS_SHEET_NAME & "$" & TableAddress & "]" & _
" WHERE Category = '" & Category & "'" & _
" AND Condition = '" & Condition & "'"
End Function
'Fill HTMLvalues object from RS (or nothing if RS has no records) and report success/failure
Function TryRSToHtmlValues(ByVal RS As Object, ByRef webValues As HtmlValues) As Boolean
If RS.EOF Then Exit Function
webValues.ConditionDescription = RecordsetHelpers.FieldToString(RS.Fields("Condition Description"))
webValues.Description1 = RecordsetHelpers.FieldToString(RS.Fields("Description 1"))
webValues.Description2 = RecordsetHelpers.FieldToString(RS.Fields("Description 2"))
TryRSToHtmlValues = True
End Function
Related
an access newbie here. I am trying to write a VBA code to query from an SQL database, and append the values into an access table. For this, i wrote below code but so far, i could only write a query and create a connection to the server. But i don't know how to bring it into the access table. Can you help me with this?
Sub getInv()
Dim RowCount As Long, ColCount As Long
Dim cnn As Object
Dim RS As Object
Set cnn = CreateObject("ADODB.Connection")
Set RS = CreateObject("ADODB.Recordset")
Dim SQLQuery As String
SQLQuery = _
"SELECT " & _
"PSDDD.SDDPP, PSDDD.SPPRD " & _
"WHERE " & _
"PSDDD.SDDPP = '2244556'" & _
"ORDER BY " & _
"PSDDD.SDDPP ASC, PSDDD.SPPRD DESC "
ConnectString = _
"DRIVER={Client Access ODBC Driver (32-bit)};" & _
"UID=abbsx;PWD=password;" & _
"SYSTEM=ABCSQT;DBQ=SSTNCHP22DB;"
cnn.Open (ConnectString)
RS.Open SQLQuery, cnn
' I believe i should put the code for writing into access table here.
'Close the Recordset and Connection
RS.Close
cnn.Close
Set RS = Nothing
Set cnn = Nothing
Exit Sub
erden. I hope this code gives you inspiration to solve your problem.
Public Function appendSelectedStudentsIntoPoolTable(Interest As String) As Long
Dim rSQL As String, rParams As String
Dim aSQL As String, aParams As String
Dim sourceTable As String, targetTable As String
sourceTable = "tStudents"
targetTable = "tStudentsPool"
'Note for targetTable: ID column not set to autonumber because to preserve
'original data as in the source table. But you can use it as PK as long no
'duplication on IDs.
rParams = "PARAMETERS [par_interest] Text(50); "
rSQL = rParams & "SELECT ID, Email, FirstName " & _
"FROM " & sourceTable & _
" WHERE Interest = par_interest;"
aParams = "PARAMETERS [par_ID] Long, [par_Email] Text(255), " & _
"[par_FirstName] Text(50); "
aSQL = aParams & "INSERT INTO " & targetTable & _
" (ID, Email, FirstName) " & _
"VALUES (par_ID, par_Email, par_FirstName);"
Dim db As DAO.Database
Dim rQDf As DAO.QueryDef
Dim aQdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim rec As Variant
Dim rsCount As Long 'change data type as needed
Dim appendedCount As Long 'same as rsCount data type
Dim i As Long 'same as rsCount data type
'On Error GoTo commit_failed
Set db = CurrentDb
Set rQDf = db.CreateQueryDef("", rSQL)
rQDf.Parameters("par_interest") = Interest
Set rs = rQDf.OpenRecordset()
With rs
On Error Resume Next: .MoveLast
On Error Resume Next: .MoveFirst
If .RecordCount > 0 Then
Do While Not rs.EOF
Set aQdf = db.CreateQueryDef("", aSQL)
aQdf.Parameters("par_ID") = !ID
'add routine(s) to check existing ID on pool table here
'before record append to pool table
'to prevent duplicate ID. For now, i skip it.
aQdf.Parameters("par_Email") = !Email
aQdf.Parameters("par_FirstName") = !FirstName
aQdf.Execute dbFailOnError
aQdf.Close
appendedCount = appendedCount + 1
.MoveNext
Loop
.Close
rQDf.Close
End If
End With
appendSelectedStudentsIntoPoolTable = appendedCount: Exit Function
commit_failed:
appendSelectedStudentsIntoPoolTable = 0
'You can put error handler here
End Function
I am newbie in connection of vba (excel) and oracle database. I have tried to look for some information but I could not find anything that would work for me.
I want to write a query that will return me only rows in which there is a specific values.
My query looks like this:
SQLStr = SQLStr = "SELECT NGKHFHCD, NGKHFNAM, NGKHGNKA, NGKHSZIC, NGKHMTRC, NGKHSNZC, NGKHGCHC, NGKHKKKS, NGKHKTKS FROM NGKH order by NGKHFHCD"
But I want to have something that will be like this SQLStr = "SELECT NGKHFHCD, NGKHFNAM, NGKHGNKA, NGKHSZIC, NGKHMTRC, NGKHSNZC, NGKHGCHC, NGKHKKKS, NGKHKTKS FROM NGKH WHERE NGKHFHCD = SHeet1(A2:A)"
I just don't want to pull out whole table from oracle, because it will take a lots of time so I thought that maybe I can return only specific rows from that table.
Also if there is no searched value in the table I would like to mark it in someway.
Is there anyway to solve it?
my code:
Sub OracleLocalConnect()
Dim RecordSet As New ADODB.RecordSet
Dim con As New ADODB.Connection
Dim ExcelRange As Range
Dim SQLStr As String
Dim ws As Worksheet
con.ConnectionString = "Provider=OraOLEDB.Oracle.1;User ID=***;Password=****;Data Source=*****;"
con.Open
Set RecordSet = CreateObject("ADODB.Recordset")
SQLStr = "SELECT GNKHFHCD, GNKHFNAM, GNKHGNKA, GNKHSZIC, GNKHMTRC, GNKHSNZC, GNKHGCHC, GNKHKKKS, GNKHKTKS FROM GNKH ORDER BY GNKHFHCD"
RecordSet.Open SQLStr, con, adOpenStatic, adLockReadOnly
Set ws = ActiveWorkbook.Sheets("Prices")
Set ExcelRange = ws.Range("A2")
ExcelRange.CopyFromRecordset RecordSet
RecordSet.Close
con.Close
Exit Sub
Exit Sub
End Sub
Untested but this would be close:
Sub OracleLocalConnect()
Dim RecordSet As New ADODB.RecordSet
Dim con As New ADODB.Connection
Dim ExcelRange As Range
Dim SQLStr As String
Dim ws As Worksheet
con.ConnectionString = "Provider=OraOLEDB.Oracle.1;User ID=***;Password=****;Data Source=*****;"
con.Open
Set RecordSet = CreateObject("ADODB.Recordset")
SQLStr = " SELECT GNKHFHCD, GNKHFNAM, GNKHGNKA, GNKHSZIC, GNKHMTRC, " & _
" GNKHSNZC, GNKHGCHC, GNKHKKKS, GNKHKTKS FROM GNKH " & _
" where " & InClause(Sheet1.Range("A2:A1000"), "GNKHFHCD", True) & _
" ORDER BY GNKHFHCD "
RecordSet.Open SQLStr, con, adOpenStatic, adLockReadOnly
Set ws = ActiveWorkbook.Sheets("Prices")
Set ExcelRange = ws.Range("A2")
ExcelRange.CopyFromRecordset RecordSet
RecordSet.Close
con.Close
End Sub
'Create an in clause for an Oracle query
Function InClause(rng As Range, colName As String, Optional quoted As Boolean = False)
'https://stackoverflow.com/questions/400255/how-to-put-more-than-1000-values-into-an-oracle-in-clause
Dim s As String, c As Range, qt As String, sep As String
qt = IIf(quoted, "'", "")
sep = ""
s = "(999, " & colName & ") in ("
For Each c In rng.Cells
If Len(c.Value) > 0 Then
s = s & sep & vbLf & "(999," & qt & c.Value & qt & ")"
sep = "," 'add comma after first pass
End If
Next c
InClause = s & ")"
End Function
my datatable is this:
and the table i need is :
i used a function to concatenate rows in ms access as follows:
Public Function GetList(SQL As String _
, Optional ColumnDelimeter As String = ", " _
, Optional RowDelimeter As String = vbCrLf) As String
'PURPOSE: to return a combined string from the passed query
'ARGS:
' 1. SQL is a valid Select statement
' 2. ColumnDelimiter is the character(s) that separate each column
' 3. RowDelimiter is the character(s) that separate each row
'RETURN VAL: Concatenated list
'DESIGN NOTES:
'EXAMPLE CALL: =GetList("Select Col1,Col2 From Table1 Where Table1.Key = " & OuterTable.Key)
Const PROCNAME = "GetList"
Const adClipString = 2
Dim oConn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim sResult As String
On Error GoTo ProcErr
Set oConn = CurrentProject.Connection
Set oRS = oConn.Execute(SQL)
sResult = oRS.GetString(adClipString, -1, ColumnDelimeter, RowDelimeter)
If Right(sResult, Len(RowDelimeter)) = RowDelimeter Then
sResult = Mid$(sResult, 1, Len(sResult) - Len(RowDelimeter))
End If
GetList = sResult
oRS.Close
oConn.Close
CleanUp:
Set oRS = Nothing
Set oConn = Nothing
Exit Function
ProcErr:
' insert error handler
Resume CleanUp
End Function
and the query i used is:
SELECT OB.Operation_Type, OB.Machine_Type, OB.Attatchment, GetList("Select Operation_Name From OB As T1 Where T1.Operation_Type = """ & [ob].[Operation_Type] & """ and T1.Machine_Type = """ & [ob].[Machine_Type] & """ and T1.Attatchment = """ & [ob].[Attatchment] & """ ",""," + ") AS Expr1
FROM ob
GROUP BY ob.Operation_Type, Machine_Type, Attatchment;
that is giving me result
i need sum of SAM of concatenated rows.
please help
Thank You
If SAM is a number field, you can simply add a SUM() aggregate. Unless I'm missing something.
SELECT OB.Operation_Type, OB.Machine_Type, OB.Attatchment,
GetList("Select Operation_Name From OB As T1 Where T1.Operation_Type = """ & [ob].[Operation_Type] & """ and T1.Machine_Type = """ & [ob].[Machine_Type] & """ and T1.Attatchment = """ & [ob].[Attatchment] & """ ",""," + ") AS Expr1,
SUM([SAM]) AS SumSAM
FROM ob
GROUP BY ob.Operation_Type, Machine_Type, Attatchment;
I am trying to run a query from the Access Query designer that is working fine in Access but when I try to bring the statement across to VBA it is giving me this error message:
Run time error too few parameters. Expected 2.
I have printed the statement in the immediate window and run it in Access and it is running without asking for parameters. I have done a number of web searches the general consensus seems to be to declare it all in VBA, including the parameters -
Private Sub CmdAppend_Click()
Dim db1 As Database
Dim mystr As Recordset2
Dim UserName As String
Dim UpdateSQL As String
Dim SelectIDSQL As String
Dim checkstr As String
If Validate_Data = True Then
UserName = Environ$("Username")
SelectIDSQL = "Select Distinct ChecklistResults.[StaffID]" _
& " From ChecklistResults" _
& " Where (((ChecklistResults.[ClientID])=[Forms]![TeamLeader]![ComClientNotFin])" _
& " And ((ChecklistResults.[DateofChecklist])=[Forms]![TeamLeader]![ComDateSelect])" _
& " AND ((ChecklistResults.[ManagerID]) Is Null));"
Debug.Print SelectIDSQL
Set db1 = CurrentDb
Set mystr = db1.OpenRecordset(SelectIDSQL)
checkstr = mystr!StaffID
If checkstr <> UserName Then
I receive the above error message when I try to set mystr to the recordset. I think I can get the recordset by following the format below but is there a way of getting the above SQL statement/assignment to work?
Dim qdf1 As DAO.QueryDef
Set qdf1 = db1.QueryDefs("Get_StaffID")
qdf1.Parameters(0) = [Forms]![TeamLeader]![ComClientNotFin]
qdf1.Parameters(1) = [Forms]![TeamLeader]![ComDateSelect]
Set rst1 = qdf1.OpenRecordset(dbOpenDynaset)
As I look at this page, I see examples where the OpenRecordSet method takes two arguments. You have an error message that says something was expecting 2 parameters. Try changing this:
Set mystr = db1.OpenRecordset(SelectIDSQL)
to this:
Set mystr = db1.OpenRecordset(SelectIDSQL, dbOpenDynaset)
Thanks for the input, I used the following code to get the result I was looking for. It uses the query SelectClientID to return the ID of the person who completed the first stage of a checklist. it then checks the person who has done the second check and if they match it returns an error message. If two different people have completed it, it uses the SQL statement to update the previous record with the second checker's ID -
Private Sub CmdAppend_Click()
Dim rst1 As Recordset2
Dim db1 As Database
Dim mystr As Recordset2
Dim UserName As String
Dim UpdateSQL As String
Dim SelectIDSQL As String
Dim checkstr As String
Dim qdf1 As DAO.QueryDef
Set db1 = CurrentDb
Set qdf1 = db1.QueryDefs("SelectClientID")
qdf1.Parameters(0) = [Forms]![TeamLeader]![ComClientNotFin]
qdf1.Parameters(1) = [Forms]![TeamLeader]![ComDateSelect]
Set rst1 = qdf1.OpenRecordset(dbOpenDynaset)
If Validate_Data = True Then
UserName = Environ$("Username")
UpdateSQL = "UPDATE ChecklistResults" _
& " SET ChecklistResults.[ManagerID] = '" & UserName & "'" _
& " WHERE (((ChecklistResults.[ClientID])=[Forms]![TeamLeader]![ComClientNotFin])" _
& " AND ((ChecklistResults.[DateofChecklist])=[Forms]![TeamLeader]![ComDateSelect])" _
& " AND ((ChecklistResults.[ManagerID]) Is Null));"
checkstr = rst1!StaffID
If checkstr <> UserName Then
DoCmd.SetWarnings False
DoCmd.RunSQL UpdateSQL
DoCmd.SetWarnings True
DoCmd.Close
Else
MsgBox ("This Checklist was created by you and cannot therefore Checked by you")
End If
Else
Exit Sub
End If
End Sub
I want to execute a select statement and put the result of it (which is only 1 record with 1 value) in a variable.
This is in VBA code in access.
Private Sub Child_Click()
Dim Childnummer As Integer
Dim childnaam As String
Childnummer = Me.Keuzelijst21.Value
DoCmd.Close
DoCmd.OpenForm "submenurubrieken", acNormal, , " rubrieknummer = " & Childnummer & ""
childnaam = rubrieknaamSQL(Childnummer)
Forms!submenurubrieken.Tv_rubrieknaam.Value = childnaam
End Sub
Public Function rubrieknaamSQL(Child As Integer)
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT rubrieknaam FROM dbo_tbl_rubriek where rubrieknummer = " & Child & ""
Set rst = CurrentDb.OpenRecordset(strSQL)
End Function
Simply have your Function return the value from the Recordset:
Public Function rubrieknaamSQL(Child As Integer)
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT rubrieknaam FROM dbo_tbl_rubriek where rubrieknummer = " & Child & ""
Set rst = CurrentDb.OpenRecordset(strSQL)
' new code:
rubrieknaamSQL = rst!rubrieknaam
rst.Close
Set rst = Nothing
End Function
You can do this in pretty much one line by using the "DLookup" Function
rubrieknaam = Nz(DLookup("rubrieknaam ", "dbo_tbl_rubriek ", rubrieknummer & " =[Child]"), 0)
where Child is the ID of the record you are looking for.