Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88854

VBA - Delete Queries in Temp File

$
0
0

I'm using the following query to email a workbook using VBA, I'm struggling on how to delete all the queries in the new temp file that will be emailed out, any pointers or suggestions will be really appreciated.

I've came across the following bit of code which i tried adding in after savecopyas but no joy and unsure how to change it from ThisWorkbook to the tempfile

Dim pq As Object
For Each pq In ThisWorkbook.Queries
    pq.Delete
Next

The code I'm using is as follows:

Sub Test()
    Dim OlApp As Object
    Dim NewMail As Object
    Dim TempFilePath As String
    Dim FileExt As String
    Dim TempFileName As String
    Dim FileFullPath As String
    Dim MyWb As Workbook
    Dim MyWs As Worksheet
    Dim emailRng As Range, cl As Range
    Dim sTo As String

    Set MyWb = ThisWorkbook
    Set MyWs = MyWb.Sheets("Menu")

    Set emailRng = MyWs.Range("O1:O50")
    Set StartDate = MyWs.Range("B9")
    Set EndDate = MyWs.Range("B12")

    For Each cl In emailRng
        sTo = sTo & ";"& cl.Value
    Next

    sTo = Mid(sTo, 2)

    With Application
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    TempFilePath = Environ$("temp") & "\"

    FileExt = "."& LCase(Right(MyWb.Name, Len(MyWb.Name) - InStrRev(MyWb.Name, ".", , 1)))

    TempFileName = "Utilisation & Waiting List Report "& Format(Now, "dd-mmm-yy")

    FileFullPath = TempFilePath & TempFileName & FileExt

    MyWb.SaveCopyAs FileFullPath

    Set OlApp = CreateObject("Outlook.Application")
    Set NewMail = OlApp.CreateItem(0)

    strbody = "Hi All,"& vbNewLine & vbNewLine & _
              "Utilisation & Waiting List Report "& StartDate & " to "& EndDate & vbNewLine & vbNewLine & _
              "Please see attached future Utilisation for PAC, Theatre and POC Clinics for CAT and PAC and Theatre clinics for YAG along with Waiting List Figures."& vbNewLine & vbNewLine & _
              "Thanks,"& vbNewLine & _
              "SpaMedica Business Analysts"

    On Error Resume Next
    With NewMail
        .To = sTo
        .CC = ""
        .BCC = ""
        .Subject = "Utilisation Report & Waiting List "& Format(Now, "dd-mmm-yy")
        .Body = strbody
        .Attachments.Add FileFullPath '
        .Send   
    End With
    On Error GoTo 0

    Kill FileFullPath

    Set NewMail = Nothing
    Set OlApp = Nothing

    With Application
        .ScreenUpdating = True
        .EnableEvents = True
    End With

End Sub

Viewing all articles
Browse latest Browse all 88854


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>