2013-02-12 48 views
2

我在MS ACCESS中有一個數據庫,其中有一個ECount字段,其中包含一些計數 有沒有什麼辦法可以在VBA代碼中調用這個調用在那裏我正在生成一個新郵件,它應該在郵件中提取計數。如何從同一個數據庫中的VBA代碼中的MS ACCESS中提取字段

Private Sub Command_Click() 
Dim objOutlook As Outlook.Application 
Dim objEmail As Outlook.MailItem 
Dim ThisDay As Date 

ThisDay = Format(Now, "mm/dd/yy") 


Set objOutlook = CreateObject("Outlook.application") 
Set objEmail = objOutlook.CreateItem(olMailItem) 

With objEmail 
    .To = "" 
    .CC = "" 
    .Subject = "Daily Email Processed " *(Thisday) 
    .Body = "Hi," + vbNewLine + vbNewLine + vbNewLine + "Please find below the number of Emails processed for the " + vbNewLine + vbNewLine + "Email Count = " (**ECOUNT**) + vbNewLine + "O Count = " (**OCount**) 
    .Attachments.Add "" 
    .Attachments.Add "" 
    .Display 
    '.ReadReceiptRequested 

End With 
+0

哪裏ECount場?在表/查詢中? – 2013-02-12 08:42:08

+0

對不起,它在查詢... – CrashOverride 2013-02-12 08:44:45

回答

1
Dim db As DAO.Database 
Dim rs1 As DAO.Recordset 
Dim sCount As String 

Set db = CurrentDb() 
Set rs1 = db.OpenRecordset("SELECT TOP 1 ECounter FROM [Email Query]") 

If rs1.RecordCount > 0 Then 
    rs1.MoveFirst 
    sCount = rs1.Fields("ECount") 
End If 
rs1.Close 
set rs1 = Nothing 
set db = Nothing 

sCount將持有的價值

+0

給太多的參數設置爲rs1 = db.OpenRecordset(「選擇TOP 1 ECount FROM yourQuery」)錯誤@安德烈Gordeev – CrashOverride 2013-02-12 09:16:40

+1

@ user1897472好吧,用你想獲得的字段名替換ECount – 2013-02-12 09:52:33

+0

我第一次做了它並且查詢名也是這樣並且出現了錯誤Set rs1 = db.OpenRecordset(「SELECT TOP 1 ECounter FROM Email Query」)是我有什麼 – CrashOverride 2013-02-12 10:03:18

1

來檢索表/查詢奇異場的最簡單方法是使用Access的DLOOKUP功能。

所以,你可以寫:

 
    .Body = "Hi," + vbNewLine + vbNewLine + vbNewLine + _ 
     "Please find below the number of Emails processed for the " + vbNewLine + vbNewLine + _ 
     "Email Count = " + DLookup("ECount", "SourceTableOrQuery", "Criteria1 = 5 and Criteria2 = ""Test""") + vbNewLine + _ 
     "O Count = " + DLookup("OCount", "SourceTableOrQuery") 

另外,如果你沒有計數還,但要計算的項目數,您可以使用「DCount`功能。

+0

我在這裏得到一個錯誤--- .Body =「嗨,」+ vbNewLine + vbNewLine + vbNewLine +「電子郵件處理爲」&ThisDay + vbNewLine + vbNewLine +「電子郵件Count =「+ DLookup(」Ecounter「,」Email Query「)+ vbNewLine +」Outbound Count =「+ DLookup(」Ecounter「,」Email Query「) – CrashOverride 2013-02-12 09:06:57

+1

當你執行''時會發生什麼?立即窗口中的DLookup(「Ecounter」,「電子郵件查詢」)?電子郵件查詢真的是你的查詢的名稱和Ecounter字段的名稱?查詢只返回一行嗎? – 2013-02-12 09:19:59

+0

運行時錯誤13類型不匹配,是的,這是查詢的名稱和Ecounter是查詢存儲在查詢中的表達式。 – CrashOverride 2013-02-12 09:26:34

0
Dim db As DAO.Database 
Dim rs1 As DAO.Recordset 
Dim sCount As String 

Set db = CurrentDb() 
Set rs1 = db.OpenRecordset("SELECT TOP 1 ECounter FROM [Email Query]") 

If rs1.RecordCount > 0 Then 
    rs1.MoveFirst 
    sCount = rs1.Fields("ECount") 
End If 
rs1.Close 
set rs1 = Nothing 
set db = Nothing 
+0

感謝@Andrey Gordeev – CrashOverride 2013-02-12 10:42:47

相關問題