I am trying to convert VBA code to vb.net, im having trouble trying to search the database for a specific value around an if statement. any suggestions would be greatly appriciated.
thedatabase is called confirmation, type is the column and email is the value im looking for. could datasets work?
Function SendEmails() As Boolean
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Dim intResponse As Integer
Dim confirmation As New ADODB.Recordset
Dim details As New ADODB.Recordset
On Error GoTo Err_Execute
Dim MyConnObj As New ADODB.Connection
Dim cn As New ADODB.Connection()
MyConnObj.Open( _
"Provider = sqloledb;" & _
"Server=myserver;" & _
"Database=Email_Text;" & _
"User Id=bla;" & _
"Password=bla;")
confirmation.Open("Confirmation_list", MyConnObj)
details.Open("MessagesToSend", MyConnObj)
If details.EOF = False Then
confirmation.MoveFirst()
Do While Not confirmation.EOF
If confirmation![Type] = "Email" Then
' Create the Outlook session.
objOutlook = CreateObject("Outlook.Application")
' Create the message.
End IF
If you want really convert your code to NET then I think you should remove the ADODB objects and use the System.Data.SqlClient classes. Of course some things are more difficult now because the ADO.NET really use a detached model to work with databases.
The semi-equivalent of your code using the ADO.NET classes
....
' Use Try/Catch not the On Error Goto....'
Try
Dim conStr = "Server=myserver;Database=Email_Text;User Id=XXXX;Password=XXXXX;"
Using MyConnObj = new SqlConnection(conStr)
' Getting all the details rows and columns, '
' but you should select only the columns needed here....'
Using cmdDetails = new SqlCommand("SELECT * FROM MessagesToSend", MyConnObj)
' You need only the rows with Type=Email, so no need to retrieve all the rows'
Using cmdConfirm = new SqlCommand("SELECT * FROM Confirmation_list " & _
"WHERE [Type] = 'EMail' ", MyConnObj)
MyConnObj.Open
Using da = new SqlDataAdapter(cmdConfirm)
Dim dt = new DataTable()
da.Fill(dt)
Using reader = cmdDetails.ExecuteReader()
While reader.Read()
For Each row in dt.Rows
... ' The Outlook app should be instanced outside the loop'
Next
Loop
End Using
End Using
End Using
End Using
End Using
Catch x As Exception
MessageBox.Show("Error:" & x.Message)
End Try
Possibly the usage of the Type column is causing an issue. You might be able to get this working by doing the following:
confirmation.Fields("Type").Value
instead of
confirmation![Type]
but I would recommend you look into ADO.NET isntead of using ADODB as this is quite old now.
Related
I am new to using VB alongside Excel and am in need of help.
I have an two access databases; one having 10 columns with many rows (more than 10), and the other Database has 8 columns and the same amount of rows as the other.
What I am trying to do is to export the first 10 rows of both databases to an excel sheet (in separate sheets or in two separate excel files, either way) so that this could be emailed or printed.
I've been looking around trying to get an idea on how to do this and have tried a few ways of doing it but none of them have worked.
Additionally I'll be fine if someone can help with exporting one database through VB with the first 10 rows of the database.
Could someone please help me.
Thanks,
Andy
Assuming this is something like an Import Data button in Excel, you probably want to use ADODB to connect to your access databases, select data into a recordset, then read the recordset into an array and assign to the worksheet you want to import to (optionally at the end of existing data - this depends on whether you're importing "10 more rows" or refreshing the top 10 rows (whatever that means - guessing you have a query to get these in Access, though).
Approach would look something like this. Oh, before we begin, you'll need to add a reference (Tools -> References) to Microsoft ActiveX Data Objects 6.1.
Public Sub Test()
Dim strSQL_Query As String
Dim oCN As ADODB.Connection
Dim oCMD As ADODB.Command
Dim oRecords As ADODB.Recordset
Dim strCN As String
Dim strDBPath As String
Dim varValues As Variant
Dim wksTarget As Excel.Worksheet
Dim lngRows As Long
Dim lngCols As Long
'' Replace with the path to your DB. You could also use a dialog box to let the user choose a DB, if
'' it moves around or isn't found.
strDBPath = "C:\myFolder\myAccessFile.accdb"
strCN = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDBPath & ";" & _
"Persist Security Info=False;"
'' Replace this with a query that does what you need it to
strSQL_Query = "SELECT TOP 10 FROM [MyTable] WHERE <Conditions> ORDER BY [Column] DESC"
Set oCN = New ADODB.Connection
oCN.ConnectionString = strCN
oCN.Open
Set oCMD = New ADODB.Command
oCMD.ActiveConnection = oCN
oCMD.CommandText = strSQL_Query
Set oRecords = oCMD.Execute
If oRecords.BOF And Not oRecords.EOF Then
varValues = oRecords.GetRows
Set wksTarget = ThisWorkbook.Worksheets(1)
'' You might need 0 and 1 instead of 1 and 2 - I forget
lngCols = UBound(varValues, 1)
lngRows = UBound(varValues, 2)
wksTarget.Range("A1", wksTarget.Range("A1").Offset(lngRows, lngCols)) = varValues
End If
'' Clean up...
Set oRecords = Nothing
Set oCMD = Nothing
oCN.Close
Set oCN = Nothing
'' Do Some more stuff...
'' And finish by saving the workbook
'' 1) Check if the directory exists and create it
Dim strDir as String
strDir = "C:\Some\Path\Here"
If Dir(strDir, vbDirectory) = "" Then MkDir(strDir)
ThisWorkbook.SaveAs strDir & "YourWorkbookName.xlsm", 52 '' 52 is a constant indicating a macro enabled format
End Sub
I am using outlook 2010.
When I get an e-mail I need the following to happen:
Check the e-mail address of the sender against my ODBC database:
a. If found then save as .htm in a specific folder and write "1" on the the table's database.
b. If found two times then forward the e-mail to admin#mydomain.org with the subject: "Duplicate to sort manually"
c. If not found then forward it to admin#mydomain.org with the subject: "e-mail to be added to database"
Here is where I am now:
Public Sub ShowMessage(Item As Outlook.MailItem)
'connect to database
On Error Resume Next
Dim cnn As ADODB.Connection
Dim rst As New ADODB.Recordset
Dim cmd As ADODB.Command
Dim sSQL As String
Dim strConn As String
Set cnn = New ADODB.Connection
strConn = "DSN=mydsn;DATABASE=mydb;Trusted_Connection=yes;"
cnn.Open strConn
' Set cmd = New ADODB.Command
' cmd.ActiveConnection = cnn
sSQL = "SELECT id FROM dbo.mailing_list WHERE email_add = '" & Item.SenderEmailAddress & "'"
' cmd.CommandText = sSQL
rst.Open sSQL, cnn, adOpenStatic
email_add = rst!email_add
If rst.BOF And rst.EOF Then
' nothing found
Stop
ElseIf rst.RecordCount > 1 Then
' more than one record
Stop
Else
' one record
'
Dim Path As String
Path = "C:\"
End If
Dim strFromEmail As String
'name and format I want the email to be saved
Item.SaveAs Path, olMHTML
'if email is saved send an alert msg and if not send another one
If Item.Saved = True Then
Item.Delete
Else
MsgBox ("This email was not saved.")
End If
ex:
Set cnn = Nothing
Set cmd = Nothing
Set rst = Nothing
Set rst1 = Nothing
End Sub
Consider implementing the following scenarios:
Create a rule to run a macro which can do #a and #b.
The VBA sub should look like the following one:
Public Sub HandleNewMail(mail As MailItem)
' do something
End Sub
The Outlook object model provides the Forward method for items. It executes the Forward action for an item and returns the resulting copy as a MailItem object. The SaveAs method saves the Microsoft Outlook item to the specified path and in the format of the specified file type. If the file type is not specified, the MSG format (.msg) is used. Pass the olHTML value for the second parameter.
Handle the NewMailEx event of the Application class. It is fired when a new item is received in the Inbox.
It is up to you which way is to choose. But I'd suggest starting from the Getting Started with VBA in Outlook 2010 article in MSDN.
for the SQL-part I would use a separate module; i think the following should work. Use something like
Sub whatsoever()
Dim countsql As Integer
countsql = countemailadress("rechnung.wien#bechtle.com")
Debug.Print "COUNT = " & countsql
End Sub
to call it, then you have the answer in the "countsql" and can use this e.g. in a "case".
here the function:
Function countemailadress(searchforemail As String)
Dim mysql As String
Dim con As ADODB.connection
Dim rec As ADODB.recordset
Set con = New ADODB.connection
con.Open "DSN=mydsn;DATABASE=mydb;Trusted_Connection=yes;"
mysql = "SELECT Count(mailing_list.[email_add]) AS countemail_add FROM mailing_list where (mailing_list.[email_add]=" & searchforemail & ");"
Set rec = con.Execute(mysql)
rec.movefirst
countemailadress = rec.Fields(0)
End Function
I hope this helps,
Max
I'm struggling with a problem that involves interop and excel.
Basically, I have excel files with columns that contain "headers" and the rows beneath the columns have the data. For example, the column Age will have 12,14,etc underneath it. I am new to Interop and I'm trying to allow the user to enter the name of the column header they wish to extract data from, so if they enter "Age", it'll find age is colum B for example and then extract all the data from the proceeding rows.
I've Googled extensively and haven't found anything solid, all rather context orientated and being new to Interop makes this a little tricky.
What I've got so far:
Public Sub getExcelData(ByVal directory As String)
Dim excelAppFirstFile As Excel.Application = Nothing
excelAppFirstFile = CreateObject("Excel.Application")
Try
excelAppFirstFile.Workbooks.Open(directory)
Dim excelSheet As Excel.Worksheet = excelAppFirstFile.Worksheets(1)
Catch ex As Exception
MsgBox("There was a problem: " + ex.Message)
End Try
End Sub
I know it isn't much but I've gone in circles with ranges,etc and can't figure out how to get where I need to.
EDIT:
I forgot to add that the Column name being searched for is a variable called field which is set at an earlier stage by the user.
If all you want to do is read data in the Excel file, I suggest you to use OleDb instead of interop (which is much faster):
Dim filePath As String = "C:\Book1.xls"
Dim connectionString As String = (Convert.ToString("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=") & filePath) + ";Extended Properties=""Excel 8.0"";"
Dim connection As New OleDbConnection(connectionString)
Dim cmdText As String = "SELECT * FROM [Sheet1$]"
Dim command As New OleDbCommand(cmdText, connection)
command.Connection.Open()
Dim reader As OleDbDataReader = command.ExecuteReader()
If reader.HasRows Then
While reader.Read()
Console.WriteLine("{0}" & vbTab & "{1}", reader(0).ToString(), reader(1).ToString())
End While
End If
I'm building a client database system for a travel company.
They want to be able to retrieve all of their customer emails with one click, and have it appear on a textbox on the page, where they can copy it off and paste it into Outlook.
Currently, the textbox is called emailList, and is invisible until the button called emailGet is clicked.
However, I have no idea how to make the text appear into the textbox from an SQL query.
My SQL query is: SELECT CEmail FROM Clients. That's pretty much it.
In pseudocode, what I'm trying to do is:
sqlQuery = "SELECT CEmail FROM Clients"
Execute select query and store results (in a variable? or maybe directly to the textbox?)
emailList.Text = Result of sqlQuery
Thank you! :)
Private Sub GetEmailAddresses()
Dim sText As String = String.Empty
Dim sConnString As String = String.Empty 'Put your connection string in here
Using cn As New OleDb.OleDbConnection(sConnString)
cn.Open()
Dim cmd As New OleDb.OleDbCommand("SELECT CEmail FROM Clients", cn)
Dim r As OleDb.OleDbDataReader = cmd.ExecuteReader()
If Not r.HasRows Then Exit Sub
Do While r.Read()
sText = sText & ";" & r.GetString(0)
Loop
cn.Close()
End Using
txtboxList.Text = sText
End Sub
I'm getting the email address in encoded format like "annie#h ꇟ|(ƓƓⲘ" and i'm catching it in a string then not able to store it in server database. So how do i decode it to normal email address. or not getting which type of Encoding is it(base64/ascii/ect..).and the column type is long varchar,
machine i'm using it windows xp. I'm pulling my hair out.
Please help..
i caught the answer but i'm not sure is this the right way to do.
Now I read the record from ADODB.Recordset instead of Dataset.
is this the right way to read data.
I don't know why Dataset give me the wired email address,But using Record set i solve the issue
Here is the code sample that i use now
Dim str_query = "select * from table"
Dim objRS= New ADODB.Recordset
objRS= Cn.Execute(str_query )
Do While Not objRS.EOF
For k = 0 To objRS.Fields.Count - 1
Debug.Print objRS(k).Name & ": " & objRS(k).Value
Next
Debug.Print "_____"
objRS.MoveNext
Loop
And previously I used code this
Dim str_query = "select * from table"
Dim objRS= New ADODB.Recordset
objRS= Cn.Execute(str_query )
Dim ds As DataSet = New DataSet()
Dim da As OleDbDataAdapter = New OleDbDataAdapter
da.Fill(ds, objRS, "my_table")
For Each dr As DataRow In ds.Tables("my_table").Rows
Next