kakdativikam
New Member
- Joined
- Nov 2, 2023
- Messages
- 5
- Office Version
- 2021
- Platform
- Windows
Hi,
First and foremost, I'd like to state that I'm an absolute beginner when it comes to VBA. As the title says - I've got myself onto a journey to find and adapt a macro, which would take all rows from my table, for a single user and put them in an email, then send them in a bulk.
I have found the following VBA code that seems to cover all the requirements, but I'm getting a "Subscript out of range" error. When I debug the code, I get the following part highlighted: For counter = 0 To UBound(toArray).
Any guidance will be absolutely appreciated.
Thanks in advance.
First and foremost, I'd like to state that I'm an absolute beginner when it comes to VBA. As the title says - I've got myself onto a journey to find and adapt a macro, which would take all rows from my table, for a single user and put them in an email, then send them in a bulk.
I have found the following VBA code that seems to cover all the requirements, but I'm getting a "Subscript out of range" error. When I debug the code, I get the following part highlighted: For counter = 0 To UBound(toArray).
Any guidance will be absolutely appreciated.
VBA Code:
Option Explicit
Public Sub SendEmail()
' For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
' Working in Office 2000-2016
' Adapted by Ricardo Diaz ricardodiaz.co
Dim OutApp As Object
Dim OutMail As Object
Dim sourceTable As ListObject
Dim evalRow As ListRow
Dim counter As Long
Dim toArray() As Variant
Application.ScreenUpdating = False
Set OutApp = CreateObject("Outlook.Application")
Set sourceTable = Range("Table1").ListObject ' -> Set the table's name
On Error GoTo cleanup
' Loop through each table's rows
For Each evalRow In sourceTable.ListRows
If evalRow.Range.Cells(, 2).Value Like "?*@?*.?*" And LCase(evalRow.Range.Cells(, 3).Value) = "yes" Then
ReDim Preserve toArray(counter)
toArray(counter) = evalRow.Range.Cells(, 2).Value
counter = counter + 1
End If
Next evalRow
' Setup the email
Set OutMail = OutApp.CreateItem(0)
With OutMail
' Add gathered recipients
For counter = 0 To UBound(toArray)
.Recipients.Add (toArray(counter))
Next counter
.Subject = "Reminder"
.Body = "Dear All" _
& vbNewLine & vbNewLine & _
"Please contact us to discuss bringing " & _
"your account up to date"
'You can add files also like this
.Attachments.Add ("C:\test.txt") ' -> Adjust this path
.Send ' -> Or use Display
End With
Set OutMail = Nothing
cleanup:
Set OutApp = Nothing
Application.ScreenUpdating = True
End Sub
Thanks in advance.