SQL query in outlook macro - sql-server

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)

Related

Update VBA to SQL Server

I'm trying to retrieve and update rows in Excel/SQL and found this script which works but I tried to make it update as soon as I enter the "existencia" value instead of hitting run on the update macro, found the Worksheet change function but I'm not sure how to add it to this macro.
Private Sub Worksheet_Change(ByVal Target As Range)
Dim con As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rst As New ADODB.Recordset
Dim i As Long
Dim vDB As Variant
Dim Ws As Worksheet
con.ConnectionString = "Provider=SQLOLEDB; data source=LAPTOP\SQLEXPRESS;initial catalog=Inventario;Integrated Security=SSPI;"
con.Open
Set cmd.ActiveConnection = con
Set Ws = ActiveSheet
'The assumption is that the data on the Excel sheet is listed from a1 Cell, including fields.
vDB = Ws.Range("a1").CurrentRegion
For i = 2 To UBound(vDB, 1)
cmd.CommandText = "UPDATE Productos SET Existencia='" & vDB(i, 4) & "' WHERE id_cod=" & vDB(i, 1) & " "
cmd.Execute
Next i
con.Close
Set con = Nothing
End Sub
I have used the Worksheet_Change event to do a lot of things, but I have never ever used Worksheet_Change to update data in a SQL Server table. This doesn't really make sense, if you think about it. You can make all kinds of changes in an Excel file, all day long. People do this all the time. When you are totally done with your updates, changes, or whatever, you can push the data to a table in a database. You should not do this intermittently. Otherwise, you will have to do all kinds of cleanup in your database table(s). You don't want to create this kind of overhead for yourself.

How to update MSSQL from Excel using excel VBA

Current Situation
I have a database in MSSQL and currently it is able to link to excel the following way.
Excel table which is connected to MSSQL as follows
MSSQL table as below
Currently if I update my MSSQL table, excel table will update accordingly
What I need
I want the vice versa operation. Means whenever I update the excel table, MSSQL also needs to update. Is this possible?
I am able to do it correctly by using following code
Sub updateSqlFromExcel()
Dim cnn As ADODB.connection
Dim uSQL As String
Set cnn = New connection
cnnstr = "Provider=SQLOLEDB; " & _
"Data Source=myServer; " & _
"Initial Catalog=myDatabaseName;" & _
"User ID=username;" & _
"Password=password;" & _
"Trusted_Connection=No"
Set rngName = ActiveCell
cnn.Open cnnstr
excelId = ActiveCell.Value 'This is just an example
excelSeq = ActiveCell.Offset(0, 1).Value 'This is just an example
excelName = ActiveCell.Offset(0, 2).Value 'This is just an example
uSQL = "UPDATE myTableName SET Name = '" & excelName & "', Seq = '" & excelSeq & "' WHERE ID= '" & excelId & "' "
cnn.Execute uSQL
ActiveWorkbook.RefreshAll
MsgBox "Updated successfully. But please wait until background refresh finish before close excel", vbInformation, "Success"
cnn.Close
Set cnn = Nothing
End Sub
Please change myServer, myDatabaseName, username, passwordand myTableNameaccording to your settings in order for this macro to work. Also please add reference library Microsoft ActiveX Data Objects 2.8 Library. In order to add, press Alt+F11 and then goto Tools --> References. Scroll to Microsoft ActiveX Data Objects 2.8 Library and tick the checkbox. Press ok and you are ready to go.

VBA: Use Text Box to Populate List Box on Word User Form - Query excel data base

I want to populate a List Box on a Word User Form based on the data entered in a Text Box on the same form. Ideally this would happen in real time (using the change event I think) with each character entered in the Text Box filtering the items that appear in the List Box.
The data source is an Excel "data base" accessed using DAO. The code below works but it enters the entire data base into List Box (based on this - Link).
Private Sub UserForm_Initialize()
Dim db As DAO.Database
Dim rs As DAO.Recordset
Dim NoOfRecords As Long
'Open the database (Excel File)
Set db = OpenDatabase("C:\Users\T400\Documents\UserFormListTest.xlsx" _
, False, False, "Excel 8.0")
'Retrieve the recordset > Excel Range = "ListBoxData"
Set rs = db.OpenRecordset("SELECT * FROM ListBoxData")
' Determine the number of retrieved records
With rs
.MoveLast
NoOfRecords = .RecordCount
.MoveFirst
End With
' Set the number of Columns = number of Fields in recordset
ListBox1.ColumnCount = rs.Fields.Count
ListBox1.Column = rs.GetRows(NoOfRecords)
rs.Close
db.Close
Set rs = Nothing
Set db = Nothing
End Sub
How can I filter the data so the List Box is only populated per the Text Box? I was hoping for a simple solution like maybe modifying the SELECT * query portion of the code.
Is this possible? Or is there a better way?
As i mentioned in the comment to the question, MS Excel uses Jet database engine. So, you have to use wildcards which correspond to that database engine.
So, if you want to develop custom "search/find" functionality, you may add Combobox control on the form with these options: All, StartsWith, Contains and EndsWith. A sample code should look like (replace the name of controls to yours):
Dim sName As String
Dim sSearchType As String
Dim sQry As String
sName = TextBox1.Text
sSearchType = ComboBox1.Value
sQry = "SELECT * FROM ListBoxData "
Select Case sSearchType
Case "All"
'do nothing; return all records
Case "StartsWith"
sQry = sQry & "WHERE Name Like '" & sName & "*'"
Case "Contains"
sQry = sQry & "WHERE Name Like '*" & sName & "*'"
Case "EndWith"
sQry = sQry & "WHERE Name Like '*" & sName & "'"
End Select
Set rs = db.OpenRecordset(sQry)
'other stuff
More about wildcards, you'll find here:
Access wildcard character reference
Office: Wildcard Characters used in String Comparisons

Form ComboBox Acting As Table Column Header In Access 2007 Query

I have a form with an unbound combobox that has all the column headings for the table dbo_orderheader. What I want to do is use the combobox field to act as the table column header instead of hard coding it to a specific table column header, that way a user can search dynamically from the form on the column they choose instead of having a huge list of search boxes for each table column.
Please can anyone help on a way to do this in an access query? I am using Access 2007.
Thanks.
See Picture Attached
I'm pretty sure that there's no way to imbed a form reference as a column heading in a static query design, but you could use code behind your form to dynamically update the query design and then open the query, something like this
Private Sub btnOpenQuery_Click()
Dim cdb As DAO.Database, qdf As DAO.QueryDef
Const queryName = "flexQuery"
Set cdb = CurrentDb
DoCmd.Close acQuery, queryName, acSaveNo
On Error Resume Next
DoCmd.DeleteObject acQuery, queryName
On Error GoTo 0
Set qdf = cdb.CreateQueryDef(queryName, _
"SELECT URN, StyleNo, [" & Me.Combo3.Value & "] " & _
"FROM dbo_OrderHeader " & _
"WHERE [" & Me.Combo3.Value & "]=""" & Me.Text5.Value & """" _
)
Set qdf = Nothing
Set cdb = Nothing
DoCmd.OpenQuery queryName, acViewNormal
End Sub
Note: This sample code assumes that the "dynamic" column is a Text column, so it puts " characters around the Text5.Value when constructing the SQL statement. This code would have to be enhanced to handle other column types (e.g., no quotes for numeric columns, and perhaps # delimiters for dates).

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