MS Access Textbox Default Value Max Size Limit - vba

I have the following setup:
I have a form with unbound textbox controls. I have a procedure that fires after every AfterUpdate event.
The procedure sends the input value to a table and returns the value input in the table as the textbox's DefaultValue. The table defines unique rows by the form and control name, 2 primary keys.
After data is input, there is a button that sends data from the form in a structured way to another table and a report reads off the table. The data is input into the table in a structured way with an SQL query.
The problem is when a user inputs texts over 2048 characters in two of the fields, the code breaks due to the limit. Two of the fields on the form, on each page will likely have over 2k characters due to the nature of the forms.
My question is, can I circumvent, increase or bypass the character limit?
My code is posted below for reference if needed (Procedure called OptimizeS is loaded in every textbox on the form):
Procedure that writes the input value to the table:
Private Sub OptimizeS()
Dim cmd As ADODB.Command
Dim strForm As String
Dim strControl As String
Dim strSQL As String
Dim strCriteria As String
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strCriteria = "FormName = """ & Me.Name & """ " & _
"And ControlName = """ & Me.ActiveControl.Name & """"
' is there an existing default for this control?
If Not IsNull(DLookup("FormName", "Defaults", strCriteria)) Then
' if so then update row in table
strSQL = "UPDATE Defaults " & _
"SET DefaultVal = """ & Me.ActiveControl & """ " & _
"WHERE " & strCriteria
Else
' insert new row
strSQL = "INSERT INTO Defaults(" & _
"FormName,ControlName,DefaultVal) " & _
"VALUES(""" & Me.Name & """,""" & _
Me.ActiveControl.Name & """,""" & _
Me.ActiveControl & """)"
End If
cmd.CommandText = strSQL
cmd.Execute
End Sub
Support Procedures on the form itself:
1)
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
Dim cmd As ADODB.Command
Dim strOpened As String
Dim strForm As String
Dim strSQL As String
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strOpened = "Opened = """ & Me.Name & """ "
If Not IsNull(DLookup("Opened", "AllOpened", strOpened)) Then
strSQL = "UPDATE AllOpened " & _
"SET Opened = """ & Me.Name & """ " & _
"WHERE " & strOpened
Else
strSQL = "INSERT INTO AllOpened(Opened) " & _
"VALUES(""" & Me.Name & """)"
End If
cmd.CommandText = strSQL
cmd.Execute
End Sub
2)
Private Sub Form_Open(Cancel As Integer)
Dim cmd As ADODB.Command
Dim strCriteria As String
Dim strOpened As String
Dim varDefault As Variant
Dim varOpened As Variant
Dim strForm As String
Dim strSQL As String
Dim ctrl As Control
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strOpened = "Opened = """ & Me.Name & """ "
varOpened = DLookup("Opened", "AllOpened", strOpened)
If IsNull(varOpened) Then
strSQL = "INSERT INTO AllOpened(Opened) " & _
"VALUES(""" & Me.Name & """)"
cmd.CommandText = strSQL
cmd.Execute
Else
GoTo ErrMsg
End If
For Each ctrl In Me.Controls
strCriteria = "FormName = """ & Me.Name & """ " & _
"And ControlName = """ & ctrl.Name & """"
varDefault = DLookup("DefaultVal", "Defaults", strCriteria)
If Not IsNull(varDefault) Then
ctrl.DefaultValue = """" & varDefault & """"
End If
Next ctrl
Exit Sub
ErrMsg:
MsgBox ("The form is already open by another user. Please double-check before editing."), , "Important!!!"
End Sub
3)
Private Sub Form_Unload(Cancel As Integer)
Dim strSQL As String
Dim strForm As String
Dim cmd As ADODB.Command
Set cmd = New ADODB.Command
cmd.ActiveConnection = CurrentProject.Connection
cmd.CommandType = adCmdText
strSQL = "DELETE FROM AllOpened " & _
"WHERE Opened = """ & Me.Name & """"
cmd.CommandText = strSQL
cmd.Execute
End Sub

That's a hint in your last comment. Then try this verbose code using string variable that for sure doesn't have a 2K limit:
Dim DefaultString As String
DefaultString = Nz(varDefault)
ctrl.DefaultValue = DefaultString

Related

How to optimize a connection in vba

I am working with vba, and I am using an excel sheet to find prices using SQL code within vba. Below is an example of how it is done:
Sub connection()
Set cn = New ADODB.connection
Set cn = CreateObject("ADODB.Connection")
With cn
.Provider = "Microsoft.ACE.OLEDB.12.0"
.ConnectionString = "Data Source=" & ThisWorkbook.Path & "\" & ThisWorkbook.Name & ";" & _
"Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
.Open
End With
End Sub
Function getAddres(ByVal sTableName As String) As String
With Range(sTableName & "[#All]")
getAddres = "[" & .Parent.Name & "$" & .Address(False, False) & "]"
End With
End Function
Function Get_Coeff_1_crit(couv As String, tabelle As String, edit As String, crit1 As String) As Variant
Dim NomFeuille As String, texte_SQL As String
Dim rst As ADODB.Recordset
Dim strRangeAddress As String
Call connection
strRangeAddress = getAddres(edit)
texte_SQL = "SELECT [Coeff] FROM " & strRangeAddress & " WHERE ([Tabelle]=" & Chr(34) & tabelle & Chr(34) & _
" ) AND (( [Booléen_1] = " & crit1 & " ) OR ( [Fixe_1] = " & crit1 & " ) OR (" & crit1 & " BETWEEN [Min_1] AND [Max_1] ))"
Set rst = New ADODB.Recordset
Set rst = cn.Execute(texte_SQL)
On Error Resume Next
Get_Coeff_1_crit = 0
Get_Coeff_1_crit = rst.Fields(0).Value 'ws.Range("N7").CopyFromRecordset Rst
End Function
So I have an input of variables and this function looks for the table and correct variable combination.
My issue is that with many functions each establishing a separate connection with the excel sheet, it takes an insane amount of time to process a lot of prices.
I was wondering if anyone knows of a better way, I am rather new at vba, so I was wondering if we can store dataframes within the process like in python or is there a different way to not establish connections each time.
Thanks.
if you're looping over Get_Coeff_1_crit repeatedly then I can see why it's bogging down while it's reestablishing that connection each pass.
You'd want to do something like this inside the function,
If Not cn is Nothing then 'verify the object is instantiated
If cn.State = adStateClosed then 'State property tells if it's open
Call Connection
End If
End If
'further details on that property - https://www.w3schools.com/asp/prop_comm_state.asp

VBA Excel SQL object variable or with block variable not set

Hi I keep getting an error when trying to upload to sql. The code have been working before, but I can find what I missed when rewriting the code..
it is falling at line:
cmd.CommandText = strSQL
the code is pretty simple it takes one column in a sheet and then upload or insert it in to an SQL database. please tell me what code I'm missing, or if I declare something wrong here
Dim cn As ADODB.Connection
Set sTroksheet = ThisWorkbook.Sheets("Mlist")
Set cn = New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim strConn As String
Dim SQLstr As String
Dim SQLstrl As String
Dim Password As String
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
Dim Port_Name As String
Dim strTable As String
Dim excel_row As Long
Dim cmd As ADODB.Command
Dim rst_recordset As ADODB.Recordset
If ThisWorkbook.Sheets("Tournament Settings").Range("D4") = vbNullString
Then
MsgBox "Please setup database connection first in (DB Setup) in top menu"
Exit Sub
Else
Server_Name = Sheets("Software_Setup").Range("c3").Value
Database_Name = Sheets("Software_Setup").Range("c4").Value
User_ID = Sheets("Software_Setup").Range("c5").Value 'id user or username
Password = Sheets("Software_Setup").Range("c6").Value 'Password
Port_Name = Sheets("Software_Setup").Range("c7").Value 'Password
strConn = "Driver={MySQL ODBC 5.3 ANSI Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
cn.Open strConn
LastRow = sTroksheet.Range("A65536").End(xlUp).row
strTable = Database_Name & ".TLHMember_List"
strSQL = "INSERT INTO " & strTable & _
" (Player) VALUES "
strSQL2 = ""
For excel_row = 1 To LastRow
strSQL2 = strSQL2 & _
"('" & sTroksheet.Cells(excel_row, 1) & "') ,"
Next excel_row
strSQL = strSQL & strSQL2
Mid(strSQL, Len(strSQL), 1) = ";" ' gets rid of the last comma
cmd.CommandText = strSQL
cmd.Execute
cn.Close
End If
You need to either change this line:
Dim cmd As ADODB.Command
to
Dim cmd As New ADODB.Command
or just before error line add new line:
Set cmd = new ADODB.Command
cmd.CommandText = strSQL

Syntax error in dynamic SQL string

Please help to fix the following syntax error with Like statement. The query works with = but I need to use Like to search in the AAchange field. I think the problem is here "WHERE [AAchange] LIKE '" & "%" & _
but I'm not sure how to correct this syntax. Please see the code below:
Sub ColorNewVariant()
Dim PolicyNum As Variant
Dim bFound As Boolean
Dim cnn As ADODB.Connection 'dim the ADO collection class
Dim rs As ADODB.Recordset 'dim the ADO recordset class
Dim dbPath As String
Dim strSQL As String
Dim r As Range, cell As Range
Dim LastRow As Long
LastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
Application.EnableEvents = False
Set r = ThisWorkbook.ActiveSheet.Range("G3:G" & LastRow)
For Each cell In r
If cell.Value <> "" Then
PolicyNum = cell.Value
dbPath = PATH_MAIN & "\Report\MDL_IonTorrent.accdb"
Set cnn = New ADODB.Connection ' Initialise the collection class variable
'Connection class is equipped with a -method- Named Open
'--4 aguments-- ConnectionString, UserID, Password, Options
'ConnectionString formula--Key1=Value1;Key2=Value2;Key_n=Value_n;
cnn.Open "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & dbPath
strSQL = "SELECT [AAchange] " & _
"FROM [MDL_Table1] " & _
"WHERE [AAchange] LIKE '" & "%" & _
Replace(PolicyNum, """", """""", , , vbTextCompare) & _
""""
'Create the ADODB recordset object.
Set rs = New ADODB.Recordset 'assign memory to the recordset
'ConnectionString Open '--5 aguments--
'Source, ActiveConnection, CursorType, LockType, Options
rs.Open strSQL, cnn
bFound = Not rs.EOF
'Check if the recordset is empty.
'Close the recordet and the connection.
rs.Close
cnn.Close
'clear memory
Set rs = Nothing
Set cnn = Nothing
'Enable the screen.
If bFound Then
'MsgBox "Record exists."
Else
'MsgBox "Record not found."
'cell.Interior.ColorIndex = 8
cell.Interior.Color = RGB(255, 217, 218)
'cell.ClearComments
'cell.AddComment "New Variant"
'Fits shape around text
'cell.Comment.Shape.TextFrame.AutoSize = True
End If
End If
Next cell
Application.EnableEvents = True
End Sub
Change the quoting in your query's WHERE clause.
If you use single quotes to start and end the string value you build, you needn't bother with Replace() of double quotes within the PolicyNum value. That should make this task simpler and less confusing ...
strSQL = "SELECT [AAchange] " & _
"FROM [MDL_Table1] " & _
"WHERE [AAchange] LIKE '%" & PolicyNum & "'"
Debug.Print strSQL

vba to populate a textbox from SQL queries when combobox is change it

I have a userform with one textbox and one combobox in EXCEL.
This userform is connected to a small data base (one table with 2 columns)
Combobox is populated with the values from the first column of databasqe table
I like when the combobox is changing the textbox to be automatic populated with the corespondent value from the second column.
I have the following code but it is not working:
Please, can someone help me?
Sub PopulateTB()
Dim rs As Recordset
Dim db As database
Dim SQL As String
Set db = OpenDatabase(ThisWorkbook.Path & "\materiale.mdb")
SQL = "SELECT values_col2 FROM table_db WHERE values_col1 = " & UserForm1.ComboBox1.Value & ";"
Set rs = db.OpenRecordset(sql)
Do Until rs.EOF = True
UserForm1.TextBox1.Value = rs.Fields(SQL)
rs.MoveNext
Loop
rs.Close
Set db = Nothing
Set rs = Nothing
End Sub
Thank you!
I putted like this and it is ok
Sub PopulateTB(ByRef ctl As Control, ByVal strTable As String, ByVal strField As String, Optional ByVal strCriteria As String)
Dim strSQL As String
Dim strSQLcount As String
Dim rs As Recordset
Dim db As Database
Dim rsCount As Recordset, totalCol As Long
Dim varRecords As Variant
Set db = OpenDatabase(ThisWorkbook.Path & "\materiale.mdb")
strSQLcount = ""
strSQLcount = strSQLcount & " " & "SELECT COUNT(*) AS Total FROM " & "[" & strTable & "]"
Set rsCount = db.OpenRecordset(strSQLcount)
totalCol = rsCount!Total
rsCount.Close
Set rsCount = Nothing
strSQL = ""
strSQL = strSQL & " " & "SELECT" & "[" & strField & "]"
strSQL = strSQL & " " & "FROM " & "[" & strTable & "]"
Set rs = db.OpenRecordset(strSQL)
varRecords = rs.GetRows(totalCol)
ctl.Value = varRecords(0, Me.ComboBox1.ListIndex)
rs.Close
db.Close
Set db = Nothing
Set rs = Nothing
End Sub

Data type mismatch in VB 2008

Good day guys, I have a question. When I try to use this piece of code in my program which will add a supplier to the database, I encounter data type mismatch error. As far as I know, the status of the supplier creates the error.
How would I store the values of the radio buttons named radActive and radInactive in the database? Should I use Boolean or a String? I am using Microsoft Access as my database and the field of Status is set to Yes/No.
Here's the code.
Public Sub SupplierInsertData()
Dim conn As OleDb.OleDbConnection
Dim cmd As OleDb.OleDbCommand
Dim SupplierType As String
Dim Status As Boolean
'Check for supplier type
If frmDatabaseSupplier.radLocal.Checked = True Then
SupplierType = "Local"
ElseIf frmDatabaseSupplier.radForeign.Checked = True Then
SupplierType = "Foreign"
End If
'Check for supplier status
If frmDatabaseSupplier.radActive.Checked = True Then
Status = True
ElseIf frmDatabaseSupplier.radInactive.Checked = True Then
Status = False
End If
'For inserting of data in the database.
Dim cmdString As String = "INSERT INTO Supplier(SupplierLastName, SupplierFirstName, SupplierMiddleInitial, " & _
"SupplierCompany, SupplierType, SupplierStreetAddress, SupplierCity, SupplierContactNumber, SupplierEmail, " & _
"Status)" & _
"VALUES('" & frmDatabaseSupplier.txtSupplierLastName.Text & "','" & frmDatabaseSupplier.txtSupplierFirstName.Text & "','" & frmDatabaseSupplier.txtSupplierMiddleInitial.Text & "','" _
& frmDatabaseSupplier.txtSupplierCompany.Text & "','" & SupplierType & "', '" & frmDatabaseSupplier.txtSupplierStreetAddress.Text & "','" & frmDatabaseSupplier.txtSupplierCity.Text & "','" _
& frmDatabaseSupplier.txtSupplierContactNumber.Text & "','" & frmDatabaseSupplier.txtSupplierEmail.Text & "','" & Status & "')"
conn = New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ProjectAnalysisSystem.accdb")
cmd = New OleDb.OleDbCommand(cmdString, conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()
End Sub
Thank you!
Try to change the last part of your code.
You should use parameters to pass the values of your textbox or vars to the database engine.
And don't forget to encapsulate the disposable objects like OleDbConnection in a using statement.
Dim cmdString As String = "INSERT INTO Supplier(SupplierLastName, SupplierFirstName, SupplierMiddleInitial, " & _
"SupplierCompany, SupplierType, SupplierStreetAddress, SupplierCity, SupplierContactNumber, SupplierEmail, " & _
"Status)" & _
"VALUES(#supplierName, #supplierFirst, #supplierMiddle, #supplierCo, #supplierType, #supplierStreet, #supplierCity, " & _
"#supplierContact, #supplierMail, #status)"
Using conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ProjectAnalysisSystem.accdb")
Dim cmd As OleDbCommand = New OleDb.OleDbCommand(cmdString, conn))
cmd.Parameters.AddWithValue("#supplierName", frmDatabaseSupplier.txtSupplierLastName.Text)
cmd.Parameters.AddWithValue("#supplierFirst", frmDatabaseSupplier.txtSupplierFirstName.Text)
cmd.Parameters.AddWithValue("#supplierMiddle", frmDatabaseSupplier.txtSupplierMiddleInitial.Text)
cmd.Parameters.AddWithValue("#supplierCo", frmDatabaseSupplier.txtSupplierCompany.Text )
cmd.Parameters.AddWithValue("#supplierType", SupplierType)
cmd.Parameters.AddWithValue("#supplierStreet", frmDatabaseSupplier.txtSupplierStreetAddress.Text)
cmd.Parameters.AddWithValue("#supplierCity", frmDatabaseSupplier.txtSupplierCity.Text)
cmd.Parameters.AddWithValue("#supplierContact", frmDatabaseSupplier.txtSupplierContactNumber.Text)
cmd.Parameters.AddWithValue("#supplierMail", frmDatabaseSupplier.txtSupplierEmail.Text)
cmd.Parameters.AddWithValue("#status", Status) '<- Here the status var is correctly identified as a boolean, not as a string
conn.Open()
cmd.ExecuteNonQuery()
End Using
You have a data type mismatch error because your INSERT statement attempts to store a string value for the Status field whose data type is Yes/No.
This isn't really a VB.Net problem. You would get the very same error from Access' db engine if you were attempting the same thing from VBA. This is the output from the VBA procedure below.
INSERT INTO Supplier (Status)
VALUES('True')
Error -2147217913 (Data type mismatch in criteria expression.)
The procedure ...
Public Sub Ju_chan()
Dim cmdString As String
Dim Status As Boolean
Dim strMsg As String
On Error GoTo ErrorHandler
Status = True
cmdString = "INSERT INTO Supplier (Status)" & vbCrLf & _
"VALUES('" & Status & "')"
Debug.Print cmdString
CurrentProject.Connection.Execute cmdString
ExitHere:
On Error GoTo 0
Exit Sub
ErrorHandler:
strMsg = "Error " & Err.Number & " (" & Err.Description _
& ")"
Debug.Print strMsg
GoTo ExitHere
End Sub
Please understand this is not intended to steer you away from using parameters. I only wanted to clarify why you're getting that error.