How to Refresh combobox in Visual Basic - combobox

When a button is clicked, it populates a combo box with all the databases you have created. Another button creates a new database. How do I refresh my combobox to add the newly added database?
Here's how I populate my combo box at the start:
rs.Open "show databases", conn
While Not rs.EOF
If rs!Database <> "information_schema" Then
Combo1.AddItem rs!Database
End If
rs.MoveNext
Wend
cmdOK.Enabled = False
cmdCancel.Enabled = False
frmLogin.Height = 3300
rs.Close

If you happen to have the database name to hand, it is a simple matter of:
Combo1.AddItem "<new database name>"
Otherwise, you should refresh the database list from source:
Sub RefreshDatabaseList(ByRef conn As Connection)
Dim rs As Recordset
' Remove all previous entries.
Combo1.Clear
' Rebuild the list.
rs.Open "show databases", conn
While Not rs.EOF
If rs!Database <> "information_schema" Then
Combo1.AddItem rs!Database
End If
rs.MoveNext
Wend
End Sub

you can refresh the comboboz
Combo1.Refresh()

Related

How do I connect to a new Datasource in Access 2016 VBA?

My department uses an application created using VBA and Access 2016. It originally pointed to an Access database on one of our servers. After migrating the data to a different server, I now need it pointing to the other SQL Server database on that different server. But I can't seem to make the connection.
I have dbowner permissions on the server in question.
The original code for connection string was as follows:
'Remove the filter, close the log on form, and open the Switchboard
rst.Filter = 0
DoCmd.Close acForm, "frmUserLogOn"
'Open the Main Switchboard
DoCmd.OpenForm "frmMain", acNormal
'Open the InactiveShutDown form in Hidden mode
DoCmd.OpenForm "frmInactiveShutDown", acNormal, , , , acHidden
...
Set conn = CurrentProject.Connection
...
rstLog.Open "tblUserLog", conn, adOpenKeyset, adLockOptimistic
rstLog.AddNew
rstLog!UserID = rst!UserID
rstLog!TimeIn = Now()
rstLog.Update
My new code is as follows:
'DoCmd.OpenForm "frmInactiveShutDown", acNormal, , , , acHidden
'Commented out the above statement
...
'Set conn = CurrentProject.Connection
'==================================================================
'Start of Added Code for SQL Migration
Set conn = New ADODB.Connection
With conn
.ConnectionString = "Provider=SQLNCLI11;Data Source=(My Server Name);Initial Catalog=(My Database Name);User ID=(Username);Password=(Password)"
.Open
If .State = adStateClosed Then
MsgBox "Connection unsuccessful. Could not open connection.", vbInformation, "Error:"
End If
End With
Set rst = New ADODB.Recordset
With rst
.ActiveConnection = conn
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockOptimistic
.Open "tbl_Users"
End With
'End of Added Code for SQL Migration - See Section 2 for rest of code.
'==================================================================
...
'Section 2 of Code
'==================================================================
'Start of added code for SQL Migration
rstLog.Open "tblUserLog", conn, adOpenStatic, adLockOptimistic
rstLog.AddNew
rstLog!UserID = rst!UserID
rstLog!TimeIn = DateTime.Now()
rstLog.Update
MsgBox "Success! Connection was made successfully.", vbInformation
'End of added code for SQL Migration
'===================================================================
My form has a drop down to select list of users form a table. I added a test user in that table but that test user doesn't show up in the drop down list. Hence, I think the connection is not being made.
Do I have to enter the names for Data Source, Initial Catalog, User ID and Password in quotes? So UserID='Admin'; Password='Test'?
Anyone know what I'm doing wrong?
Basically, you have a version confusion of same named table between local Access frontend database and backend SQL Server database. Currently, your code updates the tblUserLog on the SQL Server backend side and is not the same tblUserLog on the Access frontend side which likely is the one bound to your form. Hence, why you cannot see any update as the server table is never shown.
Simply do one of two things:
Use SQL Server Version: Delete or archive the Access' version and add tblUserLog as an ODBC linked table. Be sure to remove the dbo_ or other schema prefix and keep same name tblUserLog. And since table names do not change, everything such as forms and VBA code should not need to change.
Use Access Version: Keep the local Access table, tblUserLog, and update this one in VBA which requires adding another connection object and running a recordset update on that connection. See below with prefixes of server_ and local_ on ADO objects:
' OPEN SERVER CONNECTION AND SERVER TABLE RECORDSET
Set server_conn = New ADODB.Connection
With server_conn
.ConnectionString = "Provider=SQLNCLI11;Data Source=(My Server Name);Initial Catalog=(My Database Name);User ID=(Username);Password=(Password)"
.Open
If .State = adStateClosed Then
MsgBox "Connection unsuccessful. Could not open connection.", vbInformation, "Error:"
End If
End With
Set server_rst = New ADODB.Recordset
With server_rst
.ActiveConnection = conn
.CursorLocation = adUseClient
.CursorType = adOpenStatic
.LockType = adLockOptimistic
.Open "tbl_Users"
End With
' OPEN LOCAL CONNECTION AND UPDATE LOCAL TABLE RECORDSET
Set local_conn = CurrentProject.Connection
Set local_rstLog = New ADODB.Recordset
local_rstLog.Open "tblUserLog", local_conn, adOpenStatic, adLockOptimistic
local_rstLog.AddNew
local_rstLog!UserID = server_rst!UserID ' NOTICE SERVER DATA USED HERE
local_rstLog!TimeIn = DateTime.Now()
local_rstLog.Update
...
' RELEASE RESOURCES
Set server_rst = Nothing: Set local_rstLog = Nothing
Set server_conn = Nothing: Set local_conn = Nothing

Excel/VBA/SQL - refresh not working

I've created a VBA script that updates the CommandText of an SQL connection in order to pass a parameter from Excel to a stored procedure - this works fine except that the query doesn't update itself..
Private Sub CommandButton1_Click()
Dim BillDate As Date
Dim BillDateFormat As String
BillDate = Sheets("Sheet1").Range("B4").Value
BillDateFormat = Format(BillDate, "yyyy-mm-dd")
With ActiveWorkbook.Connections("BillDateConnection").OLEDBConnection
.CommandText = "EXEC TTKWBillingTest #BillDate = '" & BillDateFormat & "'"
End With
ActiveWorkbook.Connections("BillDateConnection").Refresh
End Sub
I'm finding that the data only refreshes on the first refresh and subsequent refreshes update the CommandText but the data on the worksheet does not refresh.
I've tried adding..
ActiveWorkbook.RefreshAll
but this doesn't make any difference.
Any ideas?
Put code in ThieWorkbook object so that it fires when Excel opens
Private Sub Workbook_open()
For Each objConnection In ThisWorkbook.Connections
'Get current background-refresh value
bBackground = objConnection.OLEDBConnection.BackgroundQuery
'Temporarily disable background-refresh
objConnection.OLEDBConnection.BackgroundQuery = False
objConnection.Refresh 'Refresh this connection
'Set background-refresh value back to original value
objConnection.OLEDBConnection.BackgroundQuery = bBackground
Next
End sub
NB This can cause problems if the data connection is set to update on open! Best to remove this option from the connection manager!
To update via a button:
Private Sub Cmd_RefreshData_Click()
Application.Run "'" & ThisWorkbook.Name & "'!ThisWorkbook.Workbook_Open"
ActiveWorkbook.RefreshAll
Lbl_LastRefresh_Click
End Sub
Lbl_LastRefresh uses Now() to display the last refresh time
...I figured this out.
'Enable background refresh' needs to be deselected in the connection properties.
The table refreshes every time without this option.

getting a column value from table using vb6

I'm trying to read a particular column value from a SQL result table. I know we use RowCount in c#. But I don’t know how it is done in vb6.0
For example a c# program code:
adapter.Fill(ds);
adapter.Dispose();
con.Close();
rowCount = ds.Tables[0].Rows.Count;// ds is dataset and I read that record set is used instead of dataset
if (rowCount > 1)
{
ab = ds.Tables[0].Rows[0][3].ToString();
ad = ds.Tables[0].Rows[0][8].ToString();
}
In VB6 you have a choice of ADO, DAO or RDO. ADO is newer of the three technologies, and the one MS recommends.
ADO Example
Sub Example()
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
' Ready objects for use.
Set cn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Connect.
cn.Open "Driver={SQL Server};Server=My_Server_Name;Database=Master;Trusted_Connection=yes;"
' Fetch a recordset.
rs.Open "SELECT TOP 10 Name FROM sys.Objects", cn, adOpenStatic, adLockReadOnly
' Display value, and total recordcount.
MsgBox rs.Fields(0).Value
MsgBox rs.RecordCount
' Close and release objects.
rs.Close
cn.Close
Set rs = Nothing
Set cn = Nothing
End Sub
The ADO Recordset object has a RecordCount property. Watch out! Certain cursor types do not populate this property. See the link for more on this.
ConnectionStrings.com is a great resource for finding the right connection string for you.
For this example to work you will need to add a reference to the Microsoft ActiveX Data Objects library.

SQL query in outlook macro

Im trying to pull some information from out helpdesk system into the subject line of an email. the helpdesk system is MSSQL based
My goal is to have a form with a multi column ComboBox that inserts the results of the SQL query into a multi column combobox respectively.
I was planning to use the selected value in the combo box to insert into the subject line of an email, with some text manipulation. but I have not get that far yet :)
This code gives me the query in the combobox however the data is in two separate rows, where I would like them in the same row
can anyone tell me what I am doing wrong?
Private Sub userform_initialize()
UserForm1.ComboBox1.ColumnCount = 2
On Error GoTo UserForm_Initialize_Err
Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
cnn.Open "Provider=SQLOLEDB;Data Source=sqlserver;" & _
"Initial Catalog=databasename;" & _
"Integrated Security=SSPI;"
rst.Open "Select field1, field2 from table", _
cnn, adOpenStatic
rst.MoveFirst
With UserForm1.ComboBox1
.Clear
Do
.AddItem rst.Fields(0)
.AddItem rst.Fields(1)
rst.MoveNext
Loop Until rst.EOF
End With
UserForm_Initialize_Exit:
On Error Resume Next
rst.Close
cnn.Close
Set rst = Nothing
Set cnn = Nothing
Exit Sub
UserForm_Initialize_Err:
MsgBox Err.Number & vbCrLf & Err.Description, vbCritical, "Error!"
Resume UserForm_Initialize_Exit
You are twice adding an item to the combobox (one for each field), so of course you get separate rows. If you first put the results in a two dimensional array (arr(rowcount, 1) ) and then set the items property of the combobox to the array it should have two columns (you still may have to set the properties of the combobox to show both columns though)

Access Utility to Find a Field in MDB

HI
I want to find a particular field, which exist in tables of a Access database. Is there is any utility to find this?
Yes you can do it VBA code. I have emailed you.
Public Function FindField(fieldname As String)
Dim db As Database
Dim td As TableDef
Dim fd As Field
Set db = DBEngine(0)(0)
db.TableDefs.Refresh
For Each td In db.TableDefs
For Each fd In td.fields
If fieldname = fd.Name Then
Debug.Print td.Name
End If
Next
Next
db.Close
End Function
You can use ADO Schemas:
Function ListTablesContainingField(SelectFieldName) As String
''Tables returned will include linked tables
Dim cn As New ADODB.Connection
Dim rs As ADODB.Recordset
Dim strTempList As String
On Error GoTo Error_Trap
Set cn = CurrentProject.Connection
''Get names of all tables that have a column called <SelectFieldName>
Set rs = cn.OpenSchema(adSchemaColumns, _
Array(Empty, Empty, Empty, SelectFieldName))
''List the tables that have been selected
While Not rs.EOF
''Exclude MS system tables
If Left(rs!Table_Name, 4) <> "MSys" Then
strTempList = strTempList & "," & rs!Table_Name
End If
rs.MoveNext
Wend
ListTablesContainingField = Mid(strTempList, 2)
Exit_Here:
rs.Close
Set cn = Nothing
Exit Function
Error_Trap:
MsgBox Err.Description
Resume Exit_Here
End Function
See also: http://support.microsoft.com/kb/186246
I do a lot of maintenance and integration work in access and a vba module written by Allen Browne totally rocks.
In your immediate window type
?Findfield("myfieldname")
It will search your database (tables, queries, forms, reports) to find where a particular field name is used.
Documentation and code is here http://allenbrowne.com/ser-73.html

Resources