0

我正在尝试将 VBA 代码转换为 vb.net,我在尝试在数据库中搜索 if 语句周围的特定值时遇到了麻烦。任何建议将不胜感激。数据库称为确认,类型是列,电子邮件是我要查找的值。数据集可以工作吗?

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
4

2 回答 2

1

如果您真的想将您的代码转换为 NET,那么我认为您应该删除 ADODB 对象并使用 System.Data.SqlClient 类。当然,现在有些事情变得更加困难,因为 ADO.NET 确实使用分离模型来处理数据库。

使用 ADO.NET 类的代码的半等效项

....
' 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
于 2013-11-04T12:36:29.807 回答
0

列的使用可能Type会导致问题。您可以通过执行以下操作来完成此工作:

confirmation.Fields("Type").Value 

代替

confirmation![Type]

但我建议您研究 ADO.NET 而不是使用 ADODB,因为它现在已经很老了。

于 2013-11-04T15:51:06.540 回答