Follow Vba routine:
Dim CampoRS As string
Dim Requerido As Boolean
Dim Zero As Bollean
Dim rs As DAO.Recordset
With frmCurriculum
Set rs = dbCRM.OpenRecordset("SELECT * FROM tblCurriculum", dbOpenDynaset, dbSeeChanges, dbPessimistic)
rs.MoveFirst
For n = 0 To .Controls.Count - 1
CampoRS = .Controls.item(n).Tag
Requerido = rs.Fields(CampoRS).Required
Zero = rs.Fields(CampoRS).AllowZeroLenght
...
Using DAO, this routine get the properties "Required" and "AllowZeroLenght" of a field in a recordset.
I need get the same properties but using ADO
If you look here https://flylib.com/books/en/3.9.1.29/1/ you can see that the Field.Attributes property is a bitmask, so you can check for example
(rs.Fields("Name").Attributes and 64) = 64
(or use the adFldMayBeNull ADO constant) to check if a field is nullable, but I don't see the equivalent for "allow zero length" there.
This might be a case where you need to DAO/ADOX if you want both of those properties though.
Related
Objective: I'm building VBA code to filter through an address table SunstarAccountsInWebir_SarahTest. I want to loop through first and see if the address is "valid".
If it is not valid – export to different table.
If it is valid – it enters another nested if/then within "valid" address rows:
If their ID, external_nmad_id matches the ID of the second table 1042s_FinalOutput_7, I want to update one of the columns in the second table box13c_Address.
If it doesn't match an ID of the second table – it will be exported to a different table.
My problem is when I run my code it is returning
Run-Time error 3078: cannot find table or query
(it's breaking at the line where I compare the value of the cell (as string) against the DCount of table 2). If I remove the quotes around it I get a different error:
Type mismatch against the DCount
I feel like I'm missing something simple but can't tell what. How can I get my code to match a string value called in !external_nmad_id against the rest of the table called in my string? DCount("[ID]", StrSQL1)
Public Sub EditFinalOutput2()
'set variables
Dim i As Long
Dim qs As DAO.Recordset
Dim ss As DAO.Recordset
Dim StrSQL1 As DAO.Recordset
Dim IRSfileFormatKey As String
Dim external_nmad_id As String
Dim nmad_address_1 As String
Dim nmad_address_2 As String
Dim nmad_address_3 As String
Dim mytestwrite As String
'open reference set
Set db = CurrentDb
Set qs = db.OpenRecordset("SunstarAccountsInWebir_SarahTest")
'Set ss = db.OpenRecordset("1042s_FinalOutput_7")
'Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID
'FROM 1042s_FinalOutput_7;")
With qs.Fields
intCount = qs.RecordCount - 1
For i = 0 To intCount
If (IsNull(!nmad_address_1) Or (!nmad_address_1 = !nmad_city) Or (!nmad_address_1 = !Webir_Country) And IsNull(!nmad_address_2) Or (!nmad_address_2 = !nmad_city) Or (!nmad_address_2 = !Webir_Country) And IsNull(!nmad_address_3) Or (!nmad_address_3 = !nmad_city) Or (!nmad_address_3 = !Webir_Country)) Then
DoCmd.RunSQL "INSERT INTO Addresses_ToBeReviewed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
Else:
Set ss = db.OpenRecordset("1042s_FinalOutput_7")
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
If !external_nmad_id = DCount("[ID]", StrSQL1) Then
ss.Edit
ss.Fields("box13c_Address") = qs.Fields("nmad_address_1") & qs.Fields("nmad_address_2") & qs.Fields("nmad_address_3")
ss.Update
Else: DoCmd.SetWarnings False
DoCmd.RunSQL "INSERT INTO Addresses_NotUsed SELECT SunstarAccountsInWebir_SarahTest.* FROM SunstarAccountsInWebir_SarahTest WHERE (((SunstarAccountsInWebir_SarahTest.external_nmad_id)='" & qs!external_nmad_id & "'));"
DoCmd.SetWarnings True
End If
End If
qs.MoveNext
Next i
End With
'close reference set
qs.Close
Set qs = Nothing
ss.Close
Set ss = Nothing
End Sub
The issue is that the DCount function cannot operate directly against a Recordset.
You are declaring StrSQL1 as a RecordSet object and setting it to a RecordSet based on your Select statement.
Set StrSQL1 = db.OpenRecordset("SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;")
You are then trying to pass this RecordSet to the DCount function which cannot accept a RecordSet object as the Domain parameter. As you can see in MSDN the DCount function requires a String parameter in the second position to define the "query" that you wish to "Count". Hence the 3078 error. When you remove the quotes around [ID] in your DCount line, you get Type Mismatch as a compile error because [ID] is not a String or String variable.
After you resolve that, you might want to reconsider your If statement. You haven't provided a sample of what kind of value !external_nmad_id will contain, other than the fact that it is a String value. The DCount function is going to return the number of rows found in the Domain (query) that you told it to count, so it appears you will be comparing a string (which may possibly contain alpha characters) to a number. Access will implicitly convert the DCount numeric result to a String for the sake of the comparison, but if your !external_nmad_id String is truly 10 characters or contains alpha characters, they will never match.
You cannot use a VBA recordset inside a domain aggregate like DCount as a string literal is required for table/query name argument. Simply save your query and then reference it by name in DCount.
SQL (save as query)
SELECT RIGHT(IRSfileFormatKey, 10) As ID FROM 1042s_FinalOutput_7;
VBA
If !external_nmad_id = DCount("[ID]", "mySavedQuery") Then
...
End If
Function PrintTableDefs()
Dim aDB As DAO.Database
Dim aTD As DAO.TableDef
Dim aTableName As String
Dim aForeignTableName As String
Dim aString As String
Dim count As Integer
Set count = 0
Set aDB = CurrentDb()
For Each aTD In aDB.TableDefs
Debug.Print aTD.Name
Debug.Print aTD.Connect
Debug.Print ""
count = count + 1
Next
Debug.Print "There are " & count & "table defs."
End Function
When calling this function I get "Compile Error: Expected: =". I have noticed through other questions it is related to parentheses however being mildly unfamiliar with VBA I'm unsure where my syntax is off.
Remove the set from set count = 0
set is only for assigning object references and an Integer is not an object instance.
Alex pointed out the only issue in your function that could throw a compile error: you don't need a set to initialize your count variable, because it is not an object. The rest is correct and should not throw an error, so it is elsewhere.
However your code shows that you don't really understand what is the difference between a sub and a function and it might be helpful to explain it.
A function returns a value, a sub doesn't. That's what's make them different.
You are not returning any value so you should use a sub.
Although your code works fine, because functions that doesn't return a value are accepted by the VBA compiler, it is semantically incorrect and a bad programming habit.
You can make a proper function out of it by returning the number of tables you found (your count variable)
Sub test()
Debug.Print "There are " & PrintTableDefs() & " table defs."
End Sub
Function PrintTableDefs() As Integer
Dim aDB As DAO.Database
Dim aTD As DAO.TableDef
Dim aTableName As String
Dim aForeignTableName As String
Dim aString As String
Dim count As Integer
count = 0
Set aDB = CurrentDb
For Each aTD In aDB.TableDefs
Debug.Print aTD.Name
Debug.Print aTD.Connect
Debug.Print ""
count = count + 1
Next
PrintTableDefs = count
End Function
And if you don't need anything to be returned, make a sub:
Sub PrintTableDefs()
Dim aDB As DAO.Database
Dim aTD As DAO.TableDef
Dim aTableName As String
Dim aForeignTableName As String
Dim aString As String
Dim count As Integer
count = 0
Set aDB = CurrentDb
For Each aTD In aDB.TableDefs
Debug.Print aTD.Name
Debug.Print aTD.Connect
Debug.Print ""
count = count + 1
Next
Debug.Print "There are " & count & " table defs."
End Sub
Additionally, you don't need () when you assign the CurrentDb object :
Set aDB = CurrentDb
My experience is that when calling a function or subroutine in VBA, enclosing your parameters (or lack thereof) in parentheses will cause this error.
There are two ways I know of to handle this:
Just don't use parentheses and always call the sub or function without them. This is fine if you are going from "PrintTableDefs()" to "PrintTableDefs" but can be problematic if the call is nested in a control structure or as another parameter.
Keep your parentheses, because you like parentheses and they remind you of C based language syntax, which helps you forget you are using the sadness of VBA. In that case, always assign the value of a function to a variable "result = PrintTableDefs()" and always use the Call keyword when invoking subroutines.
As an aside: your function returns no value. You should probably replace it with a subroutine, which is done by just replacing the word "Function" with the word "Sub".
I'm wondering if anyone can help me. I'm trying to populate a public dictionary from a recordset returned from an sql table.
It all seems to work fine, except one part. I don't know if it's not counting the number of keys in the dictionary correctly, or they aren't being entered correctly but for whatever reason when I try and show the total count, it always comes back with only 1 (supposed to be around 15) and only displays the first row details.
Can anyone help?
Public UserList As New scripting.Dictionary
Sub UserDL()
Dim USList As Range
Dim USArr(0 To 11) As Variant
Call ConnecttoDB
Set Cmd = New adodb.Command: Set rs = New adodb.Recordset
With Cmd
.CommandTimeout = 30
.ActiveConnection = cn
.CommandText = "CSLL.DLUsers"
Set rs = .Execute
End With
With rs
If Not .BOF And Not .EOF Then
.MoveLast
.MoveFirst
While (Not .EOF)
For i = 1 To 11
USArr(i - 1) = rs(i)
Next i
With UserList
If Not .Exists(rs("Alias")) Then
.Add Key:=rs("Alias"), Item:=USArr
End If
End With
.MoveNext
Wend
End If
End With
IA = UserList.Items
Debug.Print UserList.Count & " Items in the dictionary"
For Each element In IA
For i = 0 To 10
Debug.Print element(i)
Next i
Next element
Set Cmd = Nothing: Set rs = Nothing ': Set UserList = Nothing
End Sub
rs("Alias") is a Field object. The default property for a Field object is Value, so normally just referring to the Field object gives us what we want - the value. However, a Dictionary can store objects (as the value or the key), so when you add an object it actually stores the object rather than the default property. So in your code, you add rs("Alias") as a key, i.e. the object and not the value. When you move to the next record, rs("Alias") is still the same object - only the value has changed. Therefore when you check if the key exists, it does. You need to add the Value property as the key.
The reason aa_dd's answer works is because it stores the value in a variable and then uses that value as the key, i.e. not the Field object.
An alternative approach is to explicitly use the Value property of the Field object...
With UserList
If Not .Exists(rs("Alias").Value) Then
.Add Key:=rs("Alias").Value, Item:=USArr
End If
End With
store rs("Alias") in a variable and then use that variable as key.
dim sKey as String
With UserList
sKey=rs("Alias")
If Not .Exists(sKey) Then
.Add sKey,USArr
End If
End With
I'm new to VBA and i need help.
I want to create vba function which takes table name as input, and distinct specific field from that table. I created function, and it works when i run it in vba immediate window (when i use debug.print command to display results). But when i call this function in sql, instead whole field values, it returns just last one. I'm not good at vba syntax so i need help to understand. Does function can return more than one value? If can, how, and if not what else to use? Here's my code:
Public Function TableInfo(tabela As String)
Dim db As Database
Dim rec As Recordset
Dim polje1 As Field, polje2 As Field
Dim sifMat As Field, pogon As Field, tipVred As Field
Set db = CurrentDb()
Set rec = db.OpenRecordset(tabela)
Set sifMat = rec.Fields("Field1")
Set pogon = rec.Fields("Field2")
Set tipVred = rec.Fields("Field3")
For Each polje1 In rec.Fields
For Each polje2 In rec.Fields
TableInfo = pogon.Value
rec.MoveNext
Next
Next
End Function
Any help is appreciated.
The problem is with this line probably:
TableInfo = pogon.Value
It runs inside the loop and returns the last value of the loop.
Instead of returning one value TableInfo, you may try to return something similar to a Collection or an Array.
Inside the loop, append values in the Collection and after the loop, return the Collection back from the function.
Edit:
I have re-written the code shared by you:
Public Function TableInfo(tabela As String) as String()
Dim db As Database
Dim rec As Recordset
Dim polje1 As Field, polje2 As Field
Dim sifMat As Field, pogon As Field, tipVred As Field
Dim returnValue() As String
Dim i as Integer
Set db = CurrentDb()
Set rec = db.OpenRecordset(tabela)
Set sifMat = rec.Fields("Field1")
Set pogon = rec.Fields("Field2")
Set tipVred = rec.Fields("Field3")
' I am not going to modify this but I think we can do away with two For Each loops.
' Just iterate over rec like
' For Each r In rec -> please use proper naming conventions and best practices
' and access each field as r("Field1") and r("Field2")
For Each polje1 In rec.Fields
For Each polje2 In rec.Fields
returnValue(i) = pogon.Value
i = i + 1
rec.MoveNext
Next
Next
TableInfo = returnValue
End Function
Please note: I have not tested this code but I assume this should work for you. Also, I have assumed that you want to return String() array. Please change the data type if you want to return some other type.
When you call the array (as posted in theghostofc's answer), you will need to do something like this:
Dim TableInfo() As String
For i = LBound(TableInfo) To UBound(TableInfo)
YourValue = TableInfo(i)
... Process some code that uses YourValue
Next i
If you're not looping through your array, you're not going to get each individual value out of it.
I have a query saved in the queries section. I am running the query from VBA. Is it possible to save the results of this query to a string?
An ADO Recordset has a GetString method which might be useful to you.
I have a query named qryListTables which looks like this:
SELECT m.Name AS tbl_name
FROM MSysObjects AS m
WHERE
(((m.Name) Not Like "msys%"
And (m.Name) Not Like "~%")
AND ((m.Type)=1))
ORDER BY m.Name;
Notice that query uses % instead of * as the wildcard character. The reason for that choice is that ADO requires ANSI wild card characters (% and _ instead of * and ?).
I can use the following function to spit out a string containing the quoted names of regular tables in my database, separated by semicolons, by calling it like this:
? DemoGetString("qryListTables", True)
Public Function DemoGetString(ByVal pQueryName As String, _
Optional ByVal AddQuotes As Boolean = False) As Variant
'* early binding requires a reference to Microsoft ActiveX
'* Data Objects Library
'Dim rs As ADODB.Recordset
'Set rs = New ADODB.Recordset
'* use late binding; no referenced needed
Dim rs As Object
Set rs = CreateObject("ADODB.Recordset")
Dim varOut As Variant
rs.Open pQueryName, CurrentProject.Connection
If AddQuotes Then
varOut = """" & rs.GetString(2, , , """;""") '2 = adClipString
' strip off last quote
If Len(varOut & vbNullString) > 0 Then
varOut = Left(varOut, Len(varOut) - 1)
End If
Else
varOut = rs.GetString(2, , , ";") '2 = adClipString
End If
rs.Close
Set rs = Nothing
DemoGetString = varOut
End Function
Ok.. taking a complete shot in the dark here...
The query you are running is literally a query... think of it as its OWN table... it can be referenced as you would any other table, and can be queried against.
If you are trying to return a single string item based on a single criteria your best bet is a Dlookup:
Lookup = Nz(DLookup(string Field, string Table, string Criteria), "")
If your looking for a group of records:
dim tsSQL as string
stSQL = "SELECT * FROM table WHERE field=criteria"
dim toRecordset as new ADODB.Recordset
toRecordset.open stSQL, CurrentProject.AccessConnection, int Keyset, int Lock
Then you can directly access the fields by:
If toRecordset.RecordCount > 0 then
String = toRecordset!FieldName
End If
W/o more information... that about it...
Also it works in the other direction as well..
You can do:
toRecordset.AddNew
toRecordset!Field = Value
toRecordset.Update
I hope somewhere in there is an answer for you.
To get the entire query you could change up the select statement from example one to "SELECT * FROM query name" and that should pull the whole thing in.