I am actually quite new to VBA but I am doing some coding to streamline my office work. I understand this would be some amateur level questions to most of you but I tried to google for quite a while and I do not find satisfactory answer.
I have an excel write up that based on the inputted parameters, It should ultimately refer to the correct sheet -> copy the selected cells -> Generate an e-Mail with the body pasting the copied cells along with an attachment
I can do most of the parts, just that I cannot reference the "Correct Sheet" as a variable in my codes. Please shed some lights on for me. Thank you.
Here are most of the codes, the rest are irrelevant and too clumsy to paste all I guess.
Sub GenerateEmail()
   Dim olApp As Object
   Dim olMailItm As Object
   Dim iCounter As Integer
   Dim Dest As Variant
   Dim SDest As String
   Dim StrAtt1 As String
   Dim rng As Range
   Set rng = Nothing
   On Error Resume Next
   Set rng = Sheets("test").Range("A1:Q500").SpecialCells(xlCellTypeVisible)
   On Error GoTo 0
   If rng Is Nothing Then
        MsgBox "The selection is not a range or the sheet is protected" & _
               vbNewLine & "please correct and try again.", vbOKOnly
        Exit Sub
   End If
   With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With
   Set olApp = CreateObject("Outlook.Application")
   Set olMailItm = olApp.CreateItem(0)
   On Error Resume Next
   With olMailItm
       SDest = ""
       StrAtt1 = ThisWorkbook.Path & "\PDF\" & Sheets("Email_Generator").Range("B16")
       .To = Worksheets("Email_Generator").Range("B14")
       .CC = "Myself"
       .BCC = ""
       .Subject = Worksheets("Email_Generator").Range("B18")
       .HTMLBody = RangetoHTML(rng)
       .attachments.Add StrAtt1
       .Display
   End With
   Set olMailItm = Nothing
   Set olApp = Nothing
End Sub
Specifically, I would like this code "Sheets("test") as a Cell in Sheet "Test" that is a variable based on the paramters I have inputted in my excel so that this code will reference to the correct worksheet
   Set rng = Sheets("test").Range("A1:Q500").SpecialCells(xlCellTypeVisible)
But when I identify the sheet as a named sheet e.g. Sheets("Email1"), it perfectly works, just that it cannot become a variable.
I hope this post is not too long to read because I tried to be as specific as possible. Thank you to all who reads this and tries to help. I really appreciate it.
 
No comments:
Post a Comment