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.
Related
I'm trying to import an Excel to Access DB, and some customer numbers cannot be imported due to Type Conversion Failure. It is 12 entries out of 66 thousand. Normally the customer number is a number, but these 12 are strings like ABCDEFT001. I tried setting the field of the table to Long Text or Short text, they are still not imported (only to ImportError table). Do you know what else I can try?
Thank you very much in advance!
P.S. I'm trying to import using DoCmd.TransferSpreadsheet
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel12Xml, "Inv level", "Path/to/file.xlsb", True, "Sheetname!"
This strategy links to the excel file, instead of directly importing it, and then selects data out of it and casts any fields that need it to the correct datatype.
Sub ImportFromExcel()
Dim pathToFile As String
Dim targetTableName As String
Dim sql As String
pathToFile = "C:\Path\To\File.xlsx"
targetTableName = "ImportResults"
'//create the link
DoCmd.TransferSpreadsheet acLink, _
acSpreadsheetTypeExcel12, _
targetTableName, _
pathToFile, _
True '//This part only if the excel file has field headers
'//import
sql = "SELECT Field1Name, CStr(CustNumber) AS CustNumber, Field3Name INTO NewImportTable FROM " & targetTableName
CurrentDb.Execute sql
'//remove the link
DoCmd.DeleteObject acTable, targetTableName
End Sub
***Two pitfalls of this code to be aware of:
1) You should delete any table with the name "NewImportTable" before running this code, or you'll get a "Table Already Exists" error.
2) If any errors happen in this Sub before you remove the link, you'll have an issue the next time it runs, as it will create a link called "ImportResults1" since "ImportResults" would still exist. The really scary thing is that no errors would be thrown here. It would create "ImportResults1" and then run your sql on "ImportResults"!!
I am trying to change the linked table address from an Access file "Hey.accdb" using VBA coding from an Excel file.
I've coded the script below in my Excel file and it prompts the error "Object required" when I run it. Can someone please help me with this problem. I've been staring at it for too long. Thanks.
Sub RunMacroinAccesswithPara2()
Set Db = CreateObject("Access.Application")
Db.OpenCurrentDatabase "D:\Database1\Hey.accdb"
Db.Visible = True
Db.AutomationSecurity = msoAutomationSecurityLow
DoCmd.TransferDatabase TransferType:=acLink, _
DatabaseType:="Microsoft Access", _
DatabaseName:="V:\Reporting\Quarterly\2018Q2\JP\Data\04\Database\Valuation_Database.mdb", _
ObjectType:=acTable, _
Source:="Valuation_Database_Adjusted", _
Destination:="Valuation_Database_Adjusted"
End Sub
DoCmd belongs to the Access application object.
So use
Db.DoCmd.TransferDatabase ' etc.
Edit
To update the link, you need the TableDef object, set its .Connect property and run .RefreshLink.
See Linked table ms access 2010 change connection string
I am getting this error on command type=0 : Run-time error:'5'. Invalid procedure call or arguement in excel
this image is being shown when
I try to run the macro while doing automation in exce
I see at least Excel 2016 puts this code line .CommandType = 0 in the code while recording a macro while getting a QueryTable. But it is definitely wrong and fails while running that recorded macro later. So do removing it.
Instead the recorded:
With ActiveSheet.QueryTables.Add(Connection:= _
"...", Destination:=Range("$A$1"))
.CommandType = 0
.Name = "..."
...
use:
With ActiveSheet.QueryTables.Add(Connection:= _
"...", Destination:=Range("$A$1"))
' .CommandType = 0
.Name = "..."
...
Hint: Recording a macro is a good start. But knowledge about the used objects according to their documentation is also necessary. So always have a look at this documentations. In this case QueryTable.CommandType Property .
I'm using powershell to automate a daily task. It is essentially a macro to refresh data linked to an external source and then sends an email out. The issue is that Excel automatically prompts for username/password whenever it tries to refresh the data. I did some digging and it can not be bypassed by setting DisplayAlert = False and cannot be changed from Excel's settings. My credentials are saved so what I really need to do is to have a script to press on "Enter".
I have the following set up currently: using Windows Scheduler, I first launch a Powershell script that'll open up Excel and run the macro to refresh the data. The macro will be stuck when Excel prompts for credentials. I have a second task which is scheduled to run 2 minutes after the first one and its purpose is to press on "Enter" to get rid of the prompt.
I have tried a couple of scripts for the second task but I just can't seem to get it right.
What I have tried is as follows:
[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate("Windows Security")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
and
$excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')
[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
Any idea on how I can bypass/accept the prompt?
Thanks in advance.
We use a solution slightly different from what you already tried. Maybe it is in the details...
[void] [System.Reflection.Assembly]::LoadWithPartialName
("'Microsoft.VisualBasic")
[Microsoft.VisualBasic.Interaction]::AppActivate("Windows Security")
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
Please share the data link for more details, however, I would simply recreate the data link programmatically if indeed there is a reason why the pass & login can be saved e.g. a macro accepting pass and login
If it's a SQL connection then it would look something like this:
Sub Recreate(serverInstance as String, database as String, userId as String, password as String)
sConn = "OLEDB;Provider=SQLOLEDB;Data Source=" & _
serverInstance & ";Initial Catalog=" & database & _
";User ID=" & userId & ";Password=" & password & ";"
Set qt = wks.QueryTables.Add(Connection:=sConn, _
Destination:=Target)
With qt
.CommandType = xlCmdSql
.CommandText = sql
.Name = sName
.RefreshStyle = xlOverwriteCells
.Refresh BackgroundQuery:=False 'Execute SQL
End With
End Sub
I have an MS access 2010 database which is connected to a MS Excel 2010 for reporting purpose. I have linked the Excel to Access using Get External Data option in excel. With few changes in the reporting requirements I had to create a new query in Access (and it has some custom function). The Custom Function is a VBA module in Access.
Unfortunately when I use the Get External Data in Excel to link my new access query, the new query (View) is not listed on the list of Table/View (Import Wizard). When I remove the Custom Function the query is displayed in the wizard.
My Custom Function to Concatenate rows (taken from another site)
Public Function ConcatADO(strSQL As String, strColDelim, _
strRowDelim, ParamArray NameList() As Variant)
Dim rs As New ADODB.Recordset
Dim strList As String
On Error GoTo Proc_Err
If strSQL <> "" Then
rs.Open strSQL, CurrentProject.Connection
strList = rs.GetString(, , strColDelim, strRowDelim)
strList = Mid(strList, 1, Len(strList) - Len(strRowDelim))
Else
strList = Join(NameList, strColDelim)
End If
ConcatADO = strList
Exit Function
Proc_Err:
ConcatADO = "***" & UCase(Err.Description)
End Function
and following is the JET SQL used in the new query (which works absolutely fine within Access)
SELECT DISTINCT
D.[Ref ID],
D.[ENTRYDATE],
D.[AUDITOR LID],
D.[Process],
D.[Auditee],
D.[Auditee Name],
D.[Account No],
D.[Auditee Manager],
D.[MaxScore],
D.[Score],
D.[Result],
ConcatADO("SELECT [COMMENTS] FROM ycube WHERE [Ref ID]=" & "'" & [d].[Ref ID] & "'" ,", "," : ") AS [Master Comment]
FROM ycube AS D;
Is it the limitation of Excel when we use Custom Function and
Is there a way around to import (rather link) above Access query to Excel