I am trying to record a macro to refresh a sql connection file using a single button in vba but it comes up with an error. On hitting the refresh button to which I have assigned the macro, it says
Run time error 91 - You attempted to use an object variable that isn't yet referencing a valid object.
Sub RefreshCRS610()
'
' RefreshCRS610 Macro
'
'
With Selection.ListObject.QueryTable
.Connection = Array( _
"OLEDB;Provider=SQLOLEDB.1;Password=FDReport;Persist Security Info=True;User ID=FDReport;Initial Catalog=M6FDBGRP;Data Source=mlirvcb00" _
, _
"1;Use Procedure for Prepare=1;Auto Translate=True;Packet Size=4096;Workstation ID=FXV10084;Use Encryption for Data=False;Tag w" _
, "ith column collation when possible=False")
.CommandType = xlCmdSql
.CommandText = Array( _
"SELECT DISTINCT OKCONO As 'Company Number', OKCUNO As 'Customer Number', OKSTAT As 'Status', OKRESP As 'Branch Resp" _
, "onsible' FROM M6FDBGRP.MPXFDTA.OCUSMA")
.Refresh BackgroundQuery:=False
End With
End Sub
I was trying to automate refreshing the sql connection table without hitting right click-> edit query->table->okay-> enter pwd again and again. Trying to just refresh the azure sql database table by one click.
Run time error 91 - You attempted to use an object variable that isn't yet referencing a valid object.
Try getting the valid Selection
object instance from the Application
or ActiveWorksheet
instances.