Generic User for Excel Connection String - string

Is it possible to have a generic user reference in the data connection string of an Excel data connection?
I have a external reference to another workbook that I would like to share with my colleagues, and in the collaboration software that we use there is a path for each user's synced folder, such as:
C:\Users\"Username"\....
Is there a prompt similar to %USERPROFILE% that I could use in this instance? Here is a full connection string example:
DSN=Excel Files;DBQ=C:\Users\"Username"\...\File.xlsx;DefaultDir=C:\Users\"Username"\...;DriverId=1046;MaxBufferSize=2048;PageTimeout=5;

To generate C:\Users\Username use: environ("HOMEDRIVE") & environ("HOMEPATH")
see Environ Function
and also Windows APIs & Wscript at Daily Dose of Excel - Get the Path to My Documents in VBA

Related

How to discover Oleobject ClassType of files?

I'm stuck how to determine files' Classtypes needed to use in code to embed these files into a Word document:
Selection.InlineShapes.AddOLEObject ClassType:="AcroExch.Document.11", _
FileName:="C:\Work\Dashbaord & ".pdf", LinkToFile:=False, _
DisplayAsIcon:=False
I need to embed csv, pdf, xlsx and txt files. How I can automatically loop all files in folders and automatically determine the ClassType of each?
In order to insert a file as an OLE Object the file type needs to have an available OLE Server installed on the machine, or it needs to be in a format that the Windows Packager mechanism can "wrap up" into an OLE type. Before you go this route you need to ensure that anyone who tries to work with such a document has corresponding OLE Server software installed on the machine on which the document is opened. Just because the machine that creates an embedded OLE object can do so doesn't mean another machine can work with the result, later on.
OLE Server software will be noted in the Registry. The Microsoft Office applications (Word, Excel, PowerPoint, etc.) are able to function as OLE Servers. In the Registry you'll find corresponding entries such as Word.Document and Excel.Workbook... or AcroExch.Document for PDF files if Microsoft Office and the Adobe Acrobat Reader are installed.
One way to figure out which ClassTypes to use would be to manually insert each file type and inspect the resulting Embed field code.
To look the ClassTypes up in the Registry, something like the following code sample can be used in Word. Word has the function System.PrivateProfileString that wraps up a Windows API call to the Registry. It can be used to retrieve and to write information. (This code does not loop the files in a directory as the question was about how to determine the ClassType. For the sake of simplicity a file extension is hard-coded.)
A file type that does not have an OLE Server won't have a . in the default value of the Registry key. A .txt file, for example, is listed as txtfile. You may have to watch out for some file types; for example on my installation a csv file is listed as Excel.CSV, which may not be what you want...
Sub RetrieveOLEInfo()
Dim fileExt As String
Dim regKey As String
Dim oleServer As String
fileExt = "docx"
regKey = "HKEY_Classes_Root\."
oleServer = System.PrivateProfileString("", regKey & fileExt, "")
'Debug.Print oleServer
If InStr(oleServer, ".") = 0 Then
Debug.Print "Insert as a Package"
Else
Debug.Print "Insert as: " & oleServer
End If
End Sub

vb.net Cannot update. Getting error "Database or object is read-only." when just trying to READ from excel file

I'm more than willing to accept other suggestions on ways to accomplish what I want to do. I am trying to read some lines from an excel spreadsheet that the user uploads to my application. The web server where this will eventually reside does not have excel installed on it, which makes referencing things like Microsoft.Office.Interop.Excel.dll in my project impossible. So I've been looking for ways to read the excel file so that will work with this situation. The best way I've found so far is to use Microsoft.Jet.OLEDB.4.0 to connect to the excel file like a datasource. Here is a small snippet of I've put together so far:
Dim excelFileName As String = "C:\\Import\\K12Mercury.xlsx"
Dim conn As New OleDb.OleDbConnection(String.Format("provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & excelFileName & "; Extended Properties='Excel 8.0;HDR=YES;'"))
conn.Open()
The program fails on the conn.Open() line with the error:
cannot update. database or object is read-only
I don't know why this is happening or if this is even the best route to use to be able to read from an excel file in an environment where excel is not installed. Will someone please help me? Thanks in advance.

Embedded MS Query connection in Excel

The original task I had was to combine two worksheets dynamically. I discovered Microsoft Query lets me do it by building queries to pull data from the worksheets. However, the data connection stored in the file has references to my local computer. Is there a way to make this "embedded" in the file instead, such that I can share the file and anyone can refresh it? Here's the connection string.
DSN=Excel Files;DBQ=C:\Users\nana\Documents\Model\Project x Model - DRAFT 2015 07 13 0410 - Copy.xlsx;DefaultDir=C:\Users\nana\Documents\Model;DriverId=1046;MaxBufferSize=2048;PageTimeout=5;
I think you can set the DSN in the code so something like this should work
currentDir = Replace(WScript.ScriptFullName,WScript.ScriptName,””)
which will give you the directory the excel file was run from and then you can change your DNS params to reflect the variable:
DSN=Excel Files;DBQ=" & currentDir & "Source.xls;DefaultDir=" & currentDir & ";DriverId=1046;FIL=excel 12.0;MaxBufferSize=2048;PageTimeout=5;
That should mean the dsn always references the same workbook...
*edit I should mention this came from here http://www.experts-exchange.com/Software/Office_Productivity/Office_Suites/MS_Office/Excel/Q_26514035.html

loading csv "Could not find installable ISAM"

Im building a program in Excel VBA to automate a process and I require data stored in a csv file to be imported. So, I'm trying to use a query table to import specific columns in a csv file.
Im using ADO to interface with the csv file using the Jet Provider OLE DB. In the connection string I have specified the provider, data source, and extended properties. Im using windows xp and office 2003, so my Excel version is 8.0. I specified the provider as Microsoft.Jet.OLEDB.4.0. My code is pasted below. When the code executes I get the error "Could not find installable ISAM" at the last line that I included in the below code. I cant find anything wrong with the syntax so I was wondering if this error could be because I dont have the correct version of Jet installed? Please see code below. Thanks
Sub Excel_QueryTable()
Dim oCn As ADODB.Connection
Dim oRS As ADODB.Recordset
Dim ConnString As String
Dim SQL As String
Dim qt As QueryTable
ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\testfile.csv;" & _
"Extended Properties=Excel 8.0;HDR=Yes; FMT=Delimited; IMEX=1"","
Set oCn = New ADODB.Connection
oCn.ConnectionString = ConnString
oCn.Open
Try this:
ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\directory\where\csv\file\is\;" & _
"Extended Properties=""text;HDR=Yes;FMT=Delimited"""
I don't think you want to use the "Excel 8.0" portion, but you aren't actually connecting to an Excel worksheet; you're connecting to a text file. Also, you had extra spaces, and connection strings are REALLY picky about those, so I've deleted them.
Note that you can set the delimiter here:
HKLM\SOFTWARE\Microsoft\Jet\4.0\Engines\Text\Format
Mine is currently CSVDelimited; other options are TabDelimited and Delimited(;)
I found this info at: http://www.connectionstrings.com/textfile
-- EDIT --
Instead of pointing to a specific .csv file, you actually point the data source to a target directory. Note my changes above, in the connection string: the filename has been removed, and the path now ends in a \.
In order to use this type of data source, you actually need to teach the driver how the file is laid out. You do this through the use of a schema.ini file.
You can create the .ini file one of two ways:
Manually edit the file by hand, in notepad, using the above link to provide usage.
Use the tool built into the ODBC Data Source Admin.
In order to use the tool, you need to actually go through the steps of creating a data source. You don't actually need the data source, but as far as I can tell, it's the only way to get to the create schema.ini creation tool.
To get there:
Go to the ODBC control panel.
Add a new DSN, type: Microsoft Text Driver (*.txt, *.csv), click Finish
On "ODBC Text Setup", uncheck Use Current Directory and select the directory where your file lives.
Click on the options button, and click on the Define Format button.
Click on the file that you want to work with, and click "Guess" to get you started, then refine the data types as necessary.
When done, click OK, and you should see a schema.ini file in the directory where your .csv file is. Open it in notepad, and make sure it looks right.
The above connection string should now work correctly, using ONLY the directory where your csv lives, not the full path to the .csv.

How to update a connection string of an excel file from a script (PS)

We have an excel file which contains a connection to a database to retreive data (with a select statement).
We want to update via a (preferrably powershell) script the connection string of that file to make it query another server instead.
So for exemple :
I have report.xlsx file which connects to server A.
I run update-connection.ps1
And when I open report.xlsx it now connects to server B.
Any idea how we could do that?
Thanks.
It should be fairly easy if you decide (are allowed) to store the connection (server name) in a worksheet. Your VBA code can dynamically build the connection string based on the value of a cell. (I would probably create a named range and use it in the code).
I don't know PowerShell but the code can look something like:
$workbook.Range("Server").Value2 = "PROD_01"
You can make the worksheet hidden if you wish, but it is not a serious security.
You could try automating Excel via PowerShell, as in this article: http://kentfinkle.com/PowershellAndExcel.aspx
If you don't want to automate Excel then you could try using something like ClosedXML in your PowerShell script: http://closedxml.codeplex.com/
You can parse the connectionstring with System.Data.Common.DbConnectionStringBuilder. Check this SO thread:
Powershell regex for connectionStrings?

Resources