How to disable the "Select Data source window in VBA" - vba

I have a excel file with macro-enabled that is used to upload the data from excel into a database. There's a button in excel to run this code. When I run the code, it has a window pop-up "Select Data Source". Does anyone how to prevent this from popping up.
Thank You
Sadly as a beginner I cannot provide the picture so I will explain.
When the button is clicked. A window is opened named "Select Data Source" with three options dBASE Files, Excel Files, MS Access Database. I need to select one of them and continue on. For me it's excel so I click this and press okay. Then it has the option of allowing me to select the workbook. Is there a way to pre-do this before so that I don't see this window.
The code is shown Below, which gives this problem.
Sub Collect_campaigns()
Dim qryCampaigns As String
Application.ScreenUpdating = False
qryCampaigns = "SELECT * FROM test.tbl_test;"
Worksheets("Campaigns").Visible = True
Sheets("Campaigns").Select
Range("A:F").Select
Selection.Clear
Range("A1").Select
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=TEST_DATASOURCE;", Destination:=Range("$A$1")).QueryTable
.CommandText = qryCampaigns
.Refresh BackgroundQuery:=False
End With

With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=TEST_DATASOURCE;", Destination:=Range("$A$1")).QueryTable
As you can see in the code above, your macro refers to ODBC DataSource named TEST_DATASOURCE. I can only assume that you have copied this file from other computer, if so you also need to create same ODBC Datasource on your machine too.
If your machine is running Windows you should check "Control Panel-->Administrative Tools-->Data Sources(ODBC)".

The pop-up window is a polite way of telling you that it cannot reconcile your datasource "ODBC;DSN=TEST_DATASOURCE;" with the available ODBC data sources. Your minimialistic approach is a good one, I think -- not putting the entire connection string in but just the name. It allows MS Query to fill in the blanks based on your ODBC connection settings).
Although less likely, it could also have something to do with the password, where the ODBC connection is rejecting the attempted use at the embedded password. Since you said your data source is Excel, I'm going to put that into the 'unlikely' category... unless your data source isn't really Excel and you were pulling our proverbial legs.
My recommendation would be to apply good programming practices: cheat and be lazy
Record macro
Create the table as you would normally in Excel, Data->From Other Sources->MS Query (or whatever)
Stop the macro
Now run the macro code on a clean workbook -- with any luck it will run fine. Then, strip out pieces of fluff code as you see fit and continue to re-test it until it breaks.

Related

Excel: Is that possible to erase names from other files using vba macro?

Note : I am a total newbie in VBA and Excel, but I know my stuff in programming. This is why I am posting this for a friend of mine.
He tried to remove all names he had in his workbook (1 workbook = 1 file, right ?), so he applied this macro he found on the web, without exactly knowing what it does :
Sub Del_Name()
Dim Loop As Integer
For Loop = ActiveWorkbook.Names.Count To 1 Step -1
If MsgBox("Erase: " & ActiveWorkbook.Names(Loop).Name & " - " & ActiveWorkbook.Names(Loop).Value & "?", vbQuestion + vbYesNo, "Confirm...") = vbYes Then
ActiveWorkbook.Names(Loop).Delete
End If
Next
End Sub
Then, in his file's name manager there are names referencing to some other files, such as :
http://randomServer:port/user/randomFolder/[file.xls]randomSheet'!$AD$6:$AF$6
\\random\folder[anotherFile.xls]anotherSheet'!#REF!
He doesn't know where this names come from.
So, his concern, and my question here : is that possible that the vba macro erased names within distant files ? Is that even possible ?
I have looked hours for information about that, some posts I have read suggest this could be possible, but I am still quite confused, any help would be much appreciated.
Thanks in advance
no. it is not possible that the vba macro erased names within remote files.
all it did was to delete a list of links that were stored in the excel file.
same as if you delete a favourite link in your web browser, you are not actually changing anything on the website that link pointed to.
it is possible to use a macro to modify remote files. you must have access to the file system that contains the file and you must have "write" permission to that file. then you could open the file and update it. or run an update SQL query. plus some other ways that i cannot think of right now.

VBA Refreshing Data Connection by selecting a new text file without adding a new table

So I've been trying to figure out how to do this but I am only able to get VBA to add new connections and not refresh the current one (without prompting the user).
Basically, I have multiple things that need to be refreshed at once and it would be far easier if I could just run this macro and have it do all of the refreshes for me without me having to manually select the dozen or so text files.
So far, the only version of this that I have been able to get to work is the following:
Set RefreshWorkbook = ThisWorkbook.Sheets(4).QueryTables _
.Add(Connection:=strFilename, _
Destination:=declinerefresh.Cells(1, 1))
With RefreshWorkbook
.TextFilePromptOnRefresh = False
.TextFileCommaDelimiter = True
.Refresh
End With
Unfortunately, this means that every time I run this script, it creates new connections in the workbook. I am hoping to be able to run some sort of script that will basically refresh the workbook and open the new file without needing any user input (because every day I have to run a bunch of different reports and compile them for comparison, oh and I can't delete the old ones).
Thanks for any advice!

Export Access Query WITHOUT Formatting

Relatively simple, but I can't seem to work it out. I want to export a query from access into a .csv (tab or comma delimited). When I do it manually through the wizard it works fine. But when I do it via vba, it comes complete with dash formatting that looks like the borders in the table!
I tried two methods and got the same results
DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen
I used it with or without "ExportSpec", which is a specification I created when exporting manually.
This is the second method:
Dim testSQL As String
Dim qd As DAO.QueryDef
testSQL = "SELECT * FROM Qry_Grade"
Set qd = db.CreateQueryDef("tmpExport", testSQL)
DoCmd.TransferText acExportDelim, , "tmpExport",_
"C:\Users\Databoe\Documents\KidsTV\grade.csv"
db.QueryDefs.Delete "tmpExport"
This is a solution I've found which seems like overkill
And this is what the output looks like:
You can see it's not actually split any of the columns when opening the file in excel and that every second line is just a string of "-"'s
What about DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, myQueryName, myExportFileName, True for direct excel file export.
I tried your approaches, but I only get formated text with your first try DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen which is as expected because it's a text export not csv.
With your second method I always get an excel compatible result. Maybe you have an error trap that hides an error and the first grade.csv is not overwritten. Use a different filename for the second method to prevent that.
Found a second trap. You don't specify full file path in first method, but in second. If C:\Users\Databoe\Documents\KidsTV is not your default document path, you have 2 grade.csv in different folders, but you maybe think that you only have one that gets overwritten.
I just ran into this problem myself, and found a great work around. It doesn't save as a .csv, but you can save as a comma delimited .txt file.
Use the export wizard on the External Data tab to export your query as a .txt file without formatting.
Once the file is exported you get a dialogue box asking if you want to save export steps. Click the box and save the export.
There is an action available in the Macro wizard called "Run Saved Import/Export." Select this action and choose your saved export from the dropdown menu.
Very frustrating that even now I cant seem to make Access export a simple csv file. I do not know why they think I need pretty formatting. Try this: open Excel, Click Get Data, From Database, From MicroSoft Access Database. Select the Access Database you wish to export from. Select the table/query we want saved as an csv. This will set up a link to this table. Once imported, save the Excel file to an csv file.

Access not finding an excel file which was created in vba on a network

I have code that opens & alters an excel table, saves it to a new (network) location, and then imports data from the newly formatted excel. The issue I have is that the code can't find the newly created file, saying it doesn't exist. I've played around with adding a 'pause' function, but I'm wondering if there's a way to refresh the network link in vba? Or is there a better method? Files will vary by size.
If I add a break in the code and let it sit for a few minutes it finds the file fine.
Private Sub btnImport_Click()
[other code]
'save excel file onto network location
xlApp.ActiveWorkbook.SaveAs ("\\network\file.xlsx")
xlApp.Quit
'Import file to temp table.
DoCmd.TransferSpreadsheet acImport,acSpreadsheetTypeExcel9, "tblImport","\\network\file.xlsx", True
End sub
Run-time error '3011': The Microsoft Access database engine could not find the object '\network\file.xlsx'. Make sure the object exists and that you spell its name and the path name correctly.
Free up the Excel resources when finished:
xlApp.Quit
'free any other Excel resources, then..
Set xlApp = Nothing
If it is a network issue and you need a delay then you can use Application.OnTime. For 15 seconds:
Application.OnTime Now + TimeValue("00:00:15"), "my_Procedure"
This will run your procedure (my_Procedure()) after the delay, and this procedure can perform the import.

Intermittent error when attempting to control another database

I have the following code:
Dim obj As New Access.Application
obj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb")
obj.Run "Routine"
obj.CloseCurrentDatabase
Set obj = Nothing
The problem I'm experimenting is a pop-up that tells me Access can't set the focus on the other database. As you can see from the code, I want to run a Subroutine in another mdb. Any other way to achieve this will be appreciated.
I'm working with MS Access 2003.
This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.
I suspect this may occur when someone is working with this or the other database.
The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.
Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If
I'll make another subroutine without the MsgBox.
I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user.
This is an intermittent error. As this is production code that will be run only once a month, it's extremely difficult to reproduce, and I can't give you the exact text and number at this time. It is the second month this happened.
I suspect this may occur when someone is working with this or the other database.
The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database.
Maybe, it's because of the first line in the 'Routines' code:
If vbNo = MsgBox("Do you want to update?", vbYesNo, "Update") Then
Exit Function
End If
I'll make another subroutine without the MsgBox.
I've tried this in our development database and it works. This doesn't mean anything as the other code also workes fine in development.
I guess this error message is linked to the state of one of your databases. You are using here Jet connections and Access objects, and you might not be able, for multiple reasons (multi-user environment, unability to delete LDB Lock file, etc), to properly close your active database and open another one. So, according to me, the solution is to forget the Jet engine and to use another connexion to update the data in the "other" database.
When you say "The dataflow is to update all 'projects' once a month in one database and then make this information available in the other database", I assume that the role of your "Routine" is to update some data, either via SQL instructions or equivalent recordset updates.
Why don't you try to make the corresponding updates by opening a connexion to your other database and (1) send the corresponding SQL instructions or (2) opening recordset and making requested updates?
One idea would be for example:
Dim cn as ADODB.connexion,
qr as string,
rs as ADODB.recordset
'qr can be "Update Table_Blablabla Set ... Where ...
'rs can be "SELECT * From Table_Blablabla INNER JOIN Table_Blobloblo
set cn = New ADODB.connexion
cn.open
You can here send any SQL instruction (with command object and execute method)
or open and update any recordset linked to your other database, then
cn.close
This can also be done via an ODBC connexion (and DAO.recordsets), so you can choose your favorite objects.
If you would like another means of running the function, try the following:
Dim obj As New Access.Application
obj.OpenCurrentDatabase (CurrentProject.Path & "\Working.mdb")
obj.DoCmd.RunMacro "MyMacro"
obj.CloseCurrentDatabase
Set obj = Nothing
Where 'MyMacro' has an action of 'RunCode' with the Function name you would prefer to execute in Working.mdb
I've been able to reproduce the error in 'development'.
"This action cannot be completed because the other application is busy. Choose 'Switch To' to activate ...."
I really can't see the rest of the message, as it is blinking very fast. I guess this error is due to 'switching' between the two databases. I hope that, by educating the user, this will stop.
Philippe, your answer is, of course, correct. I'd have chosen that path if I hadn't developed the 'routine' beforehand.
"I've been able to reproduce this behaviour. It happens when the focus has to shift to the called database, but the user sets the focus ([ALT]+[TAB]) on the first database. The 'solution' was to educate the user." As it is impossible to prevent the user to switch application in Windows, I'd like to close the subject.