我创建了一个电子表格,可根据网络价格自动更新数据。我需要在VBA中编写一个代码来查找价格(可以只是一个单元格)以达到某个数字,然后一旦达到该数字就可以向指定地址发送电子邮件通知。我对如何处理这个问题有一个大概的了解,但是因为我是VBA的新手,所以当我遇到的错误以及如何解决这些错误时我很遗憾。这是我到目前为止提出的代码:
Private Sub Worksheet_Change(ByVal Target As Range)
If (VLookup(B248, B248, 1, False)) = 30 Then
Sub Send_Email_Using_VBA()
Dim Email_Subject, Email_Send_From, Email_Send_To, _
Email_Cc, Email_Bcc, Email_Body As String
Dim Mail_Object, Mail_Single As Variant
Email_Subject = "Price Alert"
Email_Send_From = "email@address.com"
Email_Send_To = "email1@address.com"
Email_Cc = "email2@address.com"
Email_Body = "Price higher than XX"
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
.Body = Email_Body
.send
End With
debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub
如果这完全被屠杀我感到抱歉,并且我很感激任何意见,这一直在推动我的发展。
由于
答案 0 :(得分:0)
VLookup
不是VBA函数,而是可以像这样使用的工作表函数:
Application.WorksheetFunction.VLookup()
您需要合并一些错误处理,但如果找不到匹配项,则会抛出错误。
答案 1 :(得分:0)
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count = 1 Then
If Target = 30 Then
Call Send_Email_Using_VBA(Target.Offset(0, -1))
End If
End If
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Sub Send_Email_Using_VBA(strItem as variant)
Dim Email_Subject As String, Email_Send_From As String, Email_Send_To As String, _
Email_Cc As String, Email_Bcc As String, Email_Body As String
Dim Mail_Object, Mail_Single As Variant
Email_Subject = "Price Alert"
Email_Send_From = "email@address.com"
Email_Send_To = "email1@address.com"
Email_Cc = "email2@address.com"
Email_Body = "Price of " & strItem & " higher than XX"
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
.Body = Email_Body
.send
End With
debugs:
If Err.Description <> "" Then MsgBox Err.Description
End Sub
这样的事情怎么样?首先,Vlookup是一个工作表函数,而不是VBA函数(有些函数都是)。所以你必须像
一样使用它Application.worksheetfunction.vlookup(etc.)
但是,Target是工作表上已更改的单元格,因此请使用它。
IF语句需要在一行上,或者需要以“如果结束”结束。
要拨打另一个子号码,请使用&#39;呼叫&#39;而不是&#39; Sub&#39;因为这将定义一个新的子。然后你必须做那个子。
我假设商品名称位于价格左侧的列中,因此我已将调用单元格的内容传递到已达到30的单元格的左侧发送子。如果你不想要,那就把它拿出来。
我还没有测试过电子邮件部分,但剩下的应该可以使用了。
您是否只想为每件商品发送一次电子邮件?或者总共一次?而且,如果价格来自例如29到31?会发生这种情况吗?