我正在尝试在VBA中使用vlookup函数,以便根据当前日期匹配excel工作表中的日期并给出相应的值。哪个会通过邮件发送。我的问题是当我声明一个变量作为Date它显示类型不匹配,但如果它是一个字符串它没有任何问题(但我还必须在文本格式的工作簿中输入相应的值)。这有点乏味。我一直在excel中使用短日期,但无法弄清楚它为什么显示类型不匹配。代码如下所示
Sub Send_Email_Using_VBA()
Dim Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body As String
Dim Ldate As Date
Dim Mail_Object, Mail_Single As Variant
Email_Subject = "Trying to send email using VBA"
Email_Send_From = "*****@*****.***"
Email_Send_To = "***@****.***"
Email_Cc = ""
Email_Bcc = ""
Ldate = Date
Email_Body = Application.VLookup(Ldate, Sheet1.Range("A1:B4"), 2, False)
On Error GoTo debugs
Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)
With Mail_Single
.Subject = Email_Subject
.To = Email_Send_To
.cc = Email_Cc
.BCC = Email_Bcc
.Body = Email_Body
.send
End With
Exit Sub
debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub
答案 0 :(得分:0)
我建议你将Sheet1.Range(“A1:B4”)更改为Sheet1.Range(“A1:B4”)。值,以便将数组传递给VLookup而不是范围对象。
VLookup
是WorksheetFunction
的成员,因此您应将Application.VLookup
更改为WorksheetFunction.VLookup
我使用了这个测试数据:
通过在vlookup
中传递范围值来传递电子邮件
Dim Email_Subject
Dim Email_Send_From As String
Dim Email_Send_To As String
Dim Email_Cc As String
Dim Email_Bcc As String
Dim Email_Body As String
Dim Mail_Object
Dim Mail_Single As Variant
Email_Subject = "Trying to send email using VBA"
Email_Send_From = "*****@*****.***"
Email_Send_To = "***@****.***"
Email_Cc = ""
Email_Bcc = ""
On Error GoTo Failed_Lookup
Email_Body = WorksheetFunction.VLookup(Format(Date, "dd-mm-yyyy"), Sheet1.Range("A1:B4").Value, 2, False)
On Error GoTo debugs
Set Mail_Object = CreateObject("Outlook.Application")
Set Mail_Single = Mail_Object.CreateItem(0)
With Mail_Single
.Subject = Email_Subject
.To = Email_Send_To
.cc = Email_Cc
.BCC = Email_Bcc
.Body = Email_Body
.send
End With
Exit Sub
debugs:
If Err.Description <> "" Then MsgBox Err.Description
Exit Sub
Failed_Lookup:
If Err.Number = 1004 Then
MsgBox "Unable to find the date " & Date
End If