Avatar of Mike Orther
Mike OrtherFlag for United States of America

asked on 

Results should Always populate the same worksheet named ProjectResults

I am running the following VBA code in Excel 2016.  Every time it runs, the results are populated on a new worksheet.  I want this code to clear anything on a single worksheet named ProjectResults and the results should always go to this same ProjectResults worksheet.

Option Explicit

 

Dim conn As ADODB.Connection

Dim rst As ADODB.Recordset

 

Sub Connect_To_SQLServer(ByVal Server_Name As String, ByVal Database_Name As String, ByVal SQL_Statement As String)

Dim strConn As String

Dim wsReport As Worksheet

Dim col As Integer

 

strConn = "Provider=SQLOLEDB;"

strConn = strConn & "Server=" & Server_Name & ";"

strConn = strConn & "Database=" & Database_Name & ";"

strConn = strConn & "Trusted_Connection=yes;"

 

Set conn = New ADODB.Connection

With conn

        .Open ConnectionString:=strConn

        .CursorLocation = adUseClient

End With

 

Set rst = New ADODB.Recordset

With rst

        .ActiveConnection = conn

        .Open Source:=SQL_Statement

       

End With

 

Set wsReport = ThisWorkbook.Worksheets.Add

With wsReport

               

        For col = 0 To rst.Fields.Count - 1

                .Cells(1, col + 1).Value = rst.Fields(col).Name

        Next col

       

        .Range("A2").CopyFromRecordset rst

       

End With

 

Set wsReport = Nothing

 

Call Close_Connections

 

End Sub

 

Private Sub Close_Connections()

 

If rst.State <> 0 Then rst.Close

If conn.State <> 0 Then conn.Close

 

'// Release Memory

Set rst = Nothing

Set conn = Nothing

 

End Sub

 

Sub Run_Report()

Dim Server_Name As String

 

 

Server_Name = "CLDGP2018TEST\DEV"

 

Call Connect_To_SQLServer(Server_Name, "MED", "SELECT PAPROJNUMBER Project_Number, REQDATE Required FROM PA01303 WHERE PA01303.REQDATE >CONVERT(DATE, '2008-07-16', 102)")

 

 

End Sub

Open in new window

VBAMicrosoft ExcelMicrosoft Office

Avatar of undefined
Last Comment
Mike Orther
Avatar of Ryan Chong
Ryan Chong
Flag of Singapore image

what you need to do is to delete the existing worksheet: ProjectResults and then rename your newly created worksheet to ProjectResults

to implement:

Option Explicit

Dim conn As ADODB.Connection
Dim rst As ADODB.Recordset

Sub Connect_To_SQLServer(ByVal Server_Name As String, ByVal Database_Name As String, ByVal SQL_Statement As String)

    Dim strConn As String
    Dim wsReport As Worksheet
    Dim col As Integer
    Dim OutputWsName As String
    
    OutputWsName = "ProjectResults"
    
    strConn = "Provider=SQLOLEDB;"
    strConn = strConn & "Server=" & Server_Name & ";"
    strConn = strConn & "Database=" & Database_Name & ";"
    strConn = strConn & "Trusted_Connection=yes;"
    
    Set conn = New ADODB.Connection
    
    With conn
            .Open ConnectionString:=strConn
            .CursorLocation = adUseClient
    End With
    
    Set rst = New ADODB.Recordset
    
    With rst
            .ActiveConnection = conn
            .Open Source:=SQL_Statement
    End With
    
    'Delete existing output
    deleteWorkSheet OutputWsName
    
    Set wsReport = ThisWorkbook.Worksheets.Add
    wsReport.Name = OutputWsName
    
    With wsReport
            For col = 0 To rst.Fields.Count - 1
                    .Cells(1, col + 1).Value = rst.Fields(col).Name
            Next col
    
            .Range("A2").CopyFromRecordset rst
    End With
    
    Set wsReport = Nothing
    
    Call Close_Connections

End Sub

Private Sub Close_Connections()

    If rst.State <> 0 Then rst.Close
    If conn.State <> 0 Then conn.Close
     
    '// Release Memory
    Set rst = Nothing
    Set conn = Nothing

End Sub

Sub Run_Report()
    
    Dim Server_Name As String
    
    Server_Name = "CLDGP2018TEST\DEV"
    
    Call Connect_To_SQLServer(Server_Name, "MED", "SELECT PAPROJNUMBER Project_Number, REQDATE Required FROM PA01303 WHERE PA01303.REQDATE >CONVERT(DATE, '2008-07-16', 102)")

End Sub

Function deleteWorkSheet(ByVal WsName As String) As Boolean
    On Error GoTo EH
    For Each ws In ThisWorkbook.Sheets
        If ws.Name = WsName Then
            Application.DisplayAlerts = False
            ws.Delete
            Application.DisplayAlerts = True
            deleteWorkSheet = True
            Exit Function
        End If
    Next
    deleteWorkSheet = False
    Exit Function
EH:
    deleteWorkSheet = False
End Function

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Norie
Norie

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of Mike Orther
Mike Orther
Flag of United States of America image

ASKER

Thank you Norie, this worked exactly as I needed it to.
Microsoft Excel
Microsoft Excel

Microsoft Excel topics include formulas, formatting, VBA macros and user-defined functions, and everything else related to the spreadsheet user interface, including error messages.

144K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo