简体   繁体   中英

How to delete Excel cells when running a macro from VBs Script

I have a VBS script which runs a VBA macro in Excel. The macro works when I manually run it in the Excel file, but when called from the VBS it won't delete out the existing data before running the queries.

Here is my VBS script dealing with Excel:

Dim xlApp, xlBook
Set xlApp = CreateObject("Excel.Application")
xlApp.DisplayAlerts = False
Set xlBook = xlApp.Workbooks.Open("Y:\Public\Eoin\Complaints Report\Complaints Report.xlsm", False)

msgbox("3")

xlApp.Run "Complaints_Report.Complaints_Report()"

WScript.Sleep 100000
xlbook.Save
xlBook.Close False
set xlBook = Nothing

xlApp.Quit
Set xlApp = Nothing

Here is my Excel VBA macro stored in a module:

Sub Complaints_Report()
    Sheets("Complaints Report").Activate
    'Clear out old detail
    Range("A2:Z10000").Clear

    'Declare variables'
    Set objMyConn = New ADODB.Connection
    Set objMyRecordset = New ADODB.Recordset
    Dim strSQL As String

    'Open Connection'
    objMyConn.ConnectionString = "Driver={Microsoft ODBC for Oracle}; " & _
            "CONNECTSTRING=(DESCRIPTION=" & _
            "(ADDRESS=(PROTOCOL=***)" & _
            "(HOST=*****)(PORT=****))" & _
            "(CONNECT_DATA=(SERVICE_NAME =*****))); uid=******; pwd=*****;"
    objMyConn.Open

    'Set and Excecute SQL Command'
    strSQL = "Select distinct * From Temp_Final_Complaints_Report"

    'Open Recordset'
    Set objMyRecordset.ActiveConnection = objMyConn
    objMyRecordset.Open strSQL

    'Copy Data to Excel'
    Sheets("Complaints Report").Range("A2").CopyFromRecordset (objMyRecordset)
End Sub

The macro returns the results but does not delete out everything in the sheet beforehand.

Two things:

  1. The Run method needs the name of the Sub to run, so there should not be parentheses:

    Change:

     xlApp.Run "Complaints_Report.Complaints_Report()" 

    To:

     xlApp.Run "Complaints_Report.Complaints_Report" 
  2. Make sure to specify the sheet explicitly when using Range , as the activation of the sheet may not be reliable

    Change:

     Range("A2:Z10000").Clear 

    To:

     Sheets("Complaints Report").Range("A2:Z10000").Clear 

You may then even remove the statement to activate the sheet, as the code will do its job without that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM