Home » excel » excel – Trying to autopopulate the body of an email using VBA, with values from a table found by using the Worksheet_Change Function

excel – Trying to autopopulate the body of an email using VBA, with values from a table found by using the Worksheet_Change Function

Posted by: admin May 14, 2020 Leave a comment

Questions:

I basically am creating this inventory spreadsheet, and when the quantity of a part goes below the reorder quantity, it will auto popup with an email to send to the correct channels to reorder the part. I have the code correctly identifying when to pop up with an email, but I wan’t the email to autofill the part number and vendor information correctly, but I can’t figure out how to get it to work. The way my table is set up, it lists Part Number first, then description, then vendor, then quantity, then reorder quantity. My code is below.

Private Sub Worksheet_Change(ByVal Target As Range)
  On Error Resume Next
  Dim xRg As Range

  If Target.Cells.Count > 1 Then Exit Sub

  Set xRg = Intersect(Range("I5:I100"), Target)
  If xRg Is Nothing Then Exit Sub

  If IsNumeric(Target.Value) And Target.Value <= Application.WorksheetFunction.VLookup(Target.Value, Sheets("Inventory List").Range("I5:J52"), 2, False) Then
    Call EmailAdmin(Target.Value)
  End If
End Sub

Sub EmailAdmin(Target)
  Dim xOutApp As Object
  Dim xOutMail As Object
  Dim xMailBody As String

  Set xOutApp = CreateObject("Outlook.Application")
  Set xOutMail = xOutApp.CreateItem(0)
  xMailBody = "Part needs to be reordered" & vbNewLine & vbNewLine & _
    "Part Number: " & vbNewLine & _
    "Description:  " & vbNewLine & _
    "Vendor:  "

On Error Resume Next
  user = Environ("Username ")
  With xOutMail
    .To = "Admin"
    .CC = user + "@gmail.com"
    .BCC = ""
    .Subject = "Equipment/Reagents Needed"

    .Body = xMailBody
    .Display 'or use .Send
  End With
On Error GoTo 0

  Set xOutMail = Nothing
  Set xOutApp = Nothing
End Sub

The picture is showing how the EmailAdmin sub does not appear if arguments are attempted to be passed in.

enter image description here

How to&Answers:

Keep your Subs simple. THe Email-Sub should not need to know where the data is – so pass it as arguments from the sub that knows where the data is…

Private Sub Worksheet_Change(ByVal Target As Range)
  ...
  Call EmailAdmin(Target.offset(0,1).value,Target.offset(0,2).value,Target.offset(0,2).value)
  ...
End Sub

Sub EmailAdmin(PartNr, Description, Vendor)
  ...
    xMailBody = "Part needs to be reordered" & vbNewLine & vbNewLine & _
    "Part Number: " & PartNr & vbNewLine & _
    "Description:  " & Description & vbNewLine & _
    "Vendor:  " & Vendor
  ...
End Sub