How Can I delete the database connection Using VB Script after refreshing and before saving the file

zakkarchiheb

New Member
Joined
Feb 16, 2023
Messages
2
Office Version
  1. 2021
Platform
  1. Windows
Hello ,

I use this VB script to automate the refresh of an excel file based on a SQL query !

My code works well but the line closing the connection contains a problem !

Here is my code !

MyDateFormat = Year(now) & Right("0" & Month(Now), 2) & _
Right("0" & Day(now), 2)

Set oExcel = CreateObject("Excel.Application")

oExcel.Application.Visible = True
oExcel.Application.ScreenUpdating = True
oExcel.Application.DisplayAlerts = False

Set oWorkbook = oExcel.Workbooks.Open("***********\Pivot Sheet.xlsx")
oWorkbook.RefreshAll

Do While oExcel.ActiveWorkbook.Connections.Count > 0
oExcel.ActiveWorkbook.Connections.Item(ActiveWorkbook.Connections.Count).Delete
Loop

oExcel.Activeworkbook.SaveAs "C:\Users\ChihebZ\Desktop\Macro vbs\Pivot Sheet_" & _
MyDateFormat & ".xlsx"

oExcel.Quit
WScript.Quit

your Help please
 

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.
So here is the focused VBA for clearing the Queries and Connections

VBA Code:
Sub ClearQueries()

Dim pq As Object

Dim q As String

For Each pq In ThisWorkbook.Queries

q = pq

ActiveWorkbook.Queries(q).Delete

Next

End Sub
 
Upvote 0
Solution

Forum statistics

Threads
1,223,243
Messages
6,170,967
Members
452,371
Latest member
Frana

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top