formatting combobox elements - vba

In my database serial-numbers are stored as an Integer.
I want to represent these numbers in a Access-frontend combobox with a different formation:
"121212345" --> "12.12.12345"
When a number is chosen it should be stored as an Integer again.
I already tried to populate the combobox by myself with some VBA code:
use a query to select all numbers
iterate all numbers and convert each to the new formation
put each converted number in the combobobox
When a selection is made i use the afterUpdate-Event to convert it back to an integer value and store it in my table.
This approach works very well but populating the combobox takes very long (4 sec for 20.000 numbers).
Is there a faster way of doing it?
When i just use the plain integer-field as recordsource, the box is populated in no time.
Edit:
'populate Combobobox:
Set db = CurrentDb
strSQL = "SELECT intSerialNumber FROM tblXXXX"
Set rs = db.OpenRecordset(strSQL)
Do While Not rs.EOF
strCurrentSerNum = rs.Fields(0).Value
Dim strSerNum As String
'xxxxxxxxx to xx.xx.xxxxx when possible
If (Len(strCurrentSerNum)) = 9 Then
strSerNum = Left(strCurrentSerNum, 2) & "." &
Mid(strCurrentSerNum, 3, 2) & "." & Right(strCurrentSerNum, 5)
Else
strSerNum = strCurrentSerNum
End If
cboSerNum.AddItem (strSerNum)
rs.MoveNext
Loop

You should use the Input Mask property for this.
A valid input mask to achieve exactly what you want is the following:
##.##.#####;;

Related

Need top3 records in MS Access

I have to create a text box in MS Access where users are able to see the top 3 records of a particular result set. So even if the query results in 5 records I only want it to display the top 3 records as three textboxes (sometimes the result may also be 1,2 or 0 records).
I took the easy way out and created a new subform which was connected to the parent form using master/child field. The textbox was placed in the details part of the subform and as a recordsource of the subfrom used the following query:
Select top 3 tbl1.column1, tbl1.column2
from tbl1
column1 is the control source for the textbox and column2 is the column I have used for master/child link.
Now the catch is that the query works fine when I use it without top 3. But when I use top 3 the textbox suddenly disappears and the subform is completely blank.
I am not able to identify the cause of the error. My guess is that it has something to do with type of the subform. Not sure.
Is there any other way I can have a text box whose number can vary on the basis of the results?(but limiting the resultset to 3)
Appreciate the help.
Textbox are not meant to hold more than 1 value.
You are trying to assign three results of 2 columns to one textbox(No can do).
Use listbox to populate as you are doing, assigning the query you just wrote in the rowsource of the list(no subforms needed). This way users will see the three records.
You could use a textbox in order to accomplish what you are trying to do. But will require some VBA coding to accomplish this.
Public function CombineValuesForTextBox() as string
Dim rst as dao.recordset
Dim strSQL as string
strSQL = "SELECT TOP 3 tbl1.Column1 as field1, tbl1.Column2 as field2 " & _
"FROM tbl1;"
set rst = currentdb.openrecordset(strsql)
if rst.recordcount = 0 then 'Checks if the recordset has records or not
CombineValuesForTextBox = "No records found"
goto EndCode 'Or replace with what actions to take if no records are found
else
rst.movelast 'Forces the recordset to fully load
rst.movefirst
do while not rst.eof
if CombineValuesForTextBox = "" or CombineValuesForTextBox = empty then
CombineValuesForTextBox = rst![field1] & " - " & rst![Field2]
else
CombineValuesForTextBox = CombineValuesForTextBox & vbcrlf & _
rst![field1] & " - " & rst![Field2]
end if
Loop
end if
rst.close
set rst = nothing
EndCode:
if not rst is nothing then
rst.close
set rst = nothing
end if
end function
Then on your form put in the code (be sure the textbox is unbound...)
me.textbox = CombineValuesForTextBox

Excel VBA insert array variable into single field in access

In my project I'm trying to save indefinite entry in excel sheet into the database (access). I'm trying to use vba to do so. However, because I don't know how long the entries will be, and I can't create so many fields in the database to fit the unknown amount of entries. And I can't INSERT an array variable into one field in the table. How can I do this?
Say I have below.
Dim SN(100) As String
SN(0)=123 'value of each entry
SN(1)=2412
'so on and so many entries
Then in the SQL statement,
"INSERT INTO [TableName] ([FieldName]) Values (SN)"
It will say RunTime Error "13" Type mismatch.
Is there any way the database field can accept a list or array as data type? So when I call the data out I can use the index to call the variable inside the list?
MS Access does not have such a data type, more primitive types like string, boolean, long. But consider joining all items in array using Join into a single string and save that string to database table. Then use Split to pull back into array as needed:
Sub ArrayIntoSQL()
Dim SN(100) As String, TN() As String
Dim SNstr As String,
SN(0) = 123 'value of each entry'
SN(1) = 2412
SNstr = Join(SN, "|") ' PIPE DELIMITER '
'123|2412|||||||||||||||||||||||||||||||||||||||||||||_
||||||||||||||||||||||||||||||||||||||||||||||||||||||'
strSQL = "INSERT INTO [TableName] ([FieldName]) Values ('" & SNstr & "')"
...
End Sub
Sub ArrayOutofSQL()
Dim SN() As String
Dim SNstr As String
strSQL = "SELECT [FieldName] FROM [TableName]"
...
Do While Not rst.EOF
SN() = Split(rst!FieldName, "|")
rst.MoveNext
Loop
...
End Sub
Because the array items may exceed Access' 255 character limit for short text data type, use the long text type (previously called memo) which does not have a declared limit.
However for best practices, wide tables (many columns) and stored objects like arrays in fields are more expensive than long tables (many rows) and linked objects. So simply save data iteratively:
For Each item in SN
strSQL = "INSERT INTO [TableName] ([FieldName]) Values (" & item & ")"
...
Next item
Of course, save values with an identifier like ID, Person, Date!

VBA to Trim all Cells in an Access Table

I'm relatively experienced with Object oriented programming, but this is my first time ever working in Office with VBA and I'm entirely stumped by the syntax. I've been doing some searching and messing with it for the past hour or so, but have been trouble actually getting a macro that runs successfully and does what I need.
I'm attempting to loop through every cell in an Access table and apply the Trim function to the contents of that cell and, as a bonus, I'd like to remove all extra spaces in the string (if any). I.e. " Trim this__string " would simply become "Trim this string" (I used the underscore there to represent individual, multiple spaces since StackOverflow didn't want to show my multiple spaces).
Any code example of doing something like this, or at least something to get me close and then I can tinker with it, would be greatly appreciated. Thanks!
You can remove leading and trailing spaces with the Trim() function in a query.
UPDATE YourTable
SET text_field = Trim(text_field);
If you will be doing this from within an Access session, you could use Replace() to replace a sequence of two spaces with a single space.
UPDATE YourTable
SET text_field = Replace(text_field, ' ', ' ');
However you may need to run that Replace() query more than once to get all the contiguous space characters down to only one.
You could also do a regular expression-based replacement with a user-defined function. I don't know if that's worth the effort, though. And a user-defined function is also only available from within an Access application session.
I overlooked the "every cell in a table" aspect. That makes this more challenging and I don't think you can solve it with a standard macro or query. You can however use VBA code to examine the TableDef, and iterate through its fields ... then call your Trim and/or Replace operations on any of those fields whose data type is text or memo.
Here's a rough code outline to identify which fields of a given table are text type.
Public Sub FindTextFields(ByVal WhichTable As String)
Dim db As DAO.Database
Dim tdf As DAO.TableDef
Dim fld As DAO.Field
Set db = CurrentDb
Set tdf = db.TableDefs(WhichTable)
For Each fld In tdf.Fields
If fld.Type = dbText Or fld.Type = dbMemo Then
Debug.Print "Do something with " & fld.Name
End If
Next
Set fld = Nothing
Set tdf = Nothing
Set db = Nothing
End Sub
Option Compare Database
Private Sub Command3_Click()
Call findField(Text1.Value)
End Sub
Public Function findField(p_myFieldName)
Dim db As Database, _
tb As TableDef, _
fd As Field
'''''''''Clearing the contents of the table
DoCmd.RunSQL "delete * from Field_Match_Found"
Set db = CurrentDb
For Each tb In db.TableDefs
For Each fd In tb.Fields
If fd.Name = p_myFieldName Then
strsql = "INSERT INTO Field_Match_Found Values (""" & tb.Name & """, """ & fd.Name & """)"
DoCmd.RunSQL strsql
End If
Next fd
Next tb
Set fd = Nothing
Set tb = Nothing
Set db = Nothing
If DCount("Account_number", "Field_Match_Found") = 0 Then
MsgBox ("No match was found")
Else
MsgBox ("Check Table Field_Match_Found for your output")
''''''''''making textbox blank for next time
Text1.Value = ""
End Function

How to read recordset as string in VBA

I have some code to read records from a database. when i read , the recordset variable modifies the table value to its own format.
For Eg:
In Database
Time value is 12345 (Not date & time) but when record set reads it, it
comes as For Eg: 23-06-2012
10:15:23
I just found that the recordset itself stores values in its own format after doing.
Set rs = CmdSqlData.Execute()
So is there any way to define a recordset as String?
Here is the code.
Dim rs As ADODB.RecordSet
Set rs = CmdSqlData.Execute()
Do While (rs.EOF = FALSE And rs.BOF = FALSE)
p = rs.GetRows(1)
cell(1,1) = p(0,0)
Loop
Can anyone please let me know how to read the data as String (as it is in database) so that no change in format will occur.
Note: I can not convert Excel cell format due to other requirements but I want to read everthing as String From Table
If you write
CStr(p(0,0))
To a cell, Excel will convert to the appropriate type for the content, so if p(0,0) is a number, the cell will be numeric.
However, if you write
ActiveSheet.Cells(1, 1) = "'" & p(0, 0)
Cell A1 will contain '2 to view, but can be manipulated as a string. This is left over from the early days of Excel, where to enter a string you had to prefix it with a single quote.
A1
2
=A1=2 FALSE
=A1="2" TRUE

VBA - Access 03 - Iterating through a list box, with an if statement to evaluate

So I have a one list box with values like DeptA, DeptB, DeptC & DeptD. I have a method that causes these to automatically populate in this list box if they are applicable. So in other words, if they populate in this list box, I want the resulting logic to say they are "Yes" in a boolean field in the table.
So to accomplish this I am trying to use this example of iteration to cycle through the list box first of all, and it works great:
dim i as integer
dim myval as string
For i = o to me.lstResults.listcount - 1
myVal = lstResults.itemdata(i)
Next i
if i debug.print myval, i get the list of data items that i want from the list box. so now i am trying to evaluate that list so that I can have an UPDATE SQL statement to update the table as i need it to be done.
so, i know this is a mistake, but this is what i tried to do (giving it as an example so that you can see what i am trying to get to here)
dim sql as string
dim i as integer
dim myval as string
dim db as database
sql = "UPDATE tblMain SET "
for i = 0 to me.lstResults.listcount - 1
myval = lstResults.itemdata(i)
If MyVal = "DeptA" Then
sql = sql & "DeptA = Yes"
ElseIF myval = "DeptB" Then
sql = sql & "DeptB = Yes"
ElseIf MyVal = "DeptC" Then
sql = sql & "DeptC = Yes"
ElseIf MyVal = "DeptD" Then
sql = sql & "DeptD = Yes"
End If
Next i
debug.print (sql)
sql = sql & ";"
set db= currentdb
db.execute(sql)
msgbox "Good Luck!"
So you can see why this is going to cause problems because the listbox that these values (DeptA, DeptB, etc) automatically populate in are dynamic....there is rarely one value in the listbox, and the list of values changes per OrderID (what the form I am using this on populates information for in the first place; unique instance).
I am looking for something that will evaluate this list one at a time (i.e. iterate through the list of values, and look for "DeptA", and if it is found add yes to the SQL string, and if it not add no to the SQL string, then march on to the next iteration). Even though the listbox populates values dynamically, they are set values, meaning i know what could end up in it.
Thanks for any help,
Justin
I don't understand what you're trying to accomplish. However, I suspect your UPDATE statement needs a WHERE clause. ('WHERE OrderID = X', with X replaced by the OrderID of the row you're editing)
I suppose you could create a dictionary object with values initially set to False.
Dim dict As Object
Set dict = CreateObject("Scripting.Dictionary")
dict.Add "DeptA", False
dict.Add "DeptB", False
' .. etc. '
Then go through the items in your listbox, changing the dict value to True.
dict(myval) = True
Finally, build your UPDATE statement based on the dictionary values.
But that all seems like too much work to me. So now I'm wondering about your table structure. Is tblMain set up similar to this?:
OrderID DeptA DeptB DeptC DeptD
------- ----- ----- ----- -----
127 True False False True
If so, consider a related table for the Dept information.
OrderID Which_Department
------- ----------------
127 DeptA
127 DeptD
The rule of thumb governing this is "columns are expensive; rows are cheap".
Edit: Seems to me you have two sets of items: SetA is all possible items; SetB is a subset of SetA. You want to produce a True for each item in SetB and a False for each SetA item which is not in SetB. Is that correct when you substitute dict (the dictionary object) for SetA and lstResults for SetB?
What I was trying to suggest is load dict with all the possible "DeptX" keys and assign them as False. Then iterate your lstResults and change each of those (in dict) to True. Afterward, build your SQL statement from dict.
Dim varKeys As Variant
Dim i As Integer
Dim strFragment As String
varKeys = dict.keys()
For i = LBound(varKeys) To UBound(varKeys)
strFragment = strFragment & ", " & varKeys(i) & " = " & dict(varKeys(i))
Next i
strFragment = Mid(strFragment, 3)
sql = sql & strFragment & "WHERECLAUSE"