I have a CSV export from an LDAP DB and I have to read data with a Classic ASP page.
The format of the CSV file is like
CRDLVR47E67L781V#1653#CORDIOLI#ELVIRA#658#elvira.cordioli#sender.at#SI
I can read the file line by line, and have to split the line manually.
If I change the # value to a comma I can access the file by column. Can I make the asp page able to access the file by column, in order to obtain the single value keeping the # separator?
My connection string is
Set oConn = Server.CreateObject("ADODB.connection")
oConn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=http://export/caselle.csv;Extended Properties='text;HDR=Yes;FMT=Delimited'"
and I can read line from the CSV file with the query
Set RS=Server.CreateObject("ADODB.recordset")
RS.open "SELECT * FROM utenti_aospbo.csv", oConn
now I can only read rs.fields(0), that output the entire line, like
CRDLVR47E67L781V#1653#CORDIOLI#ELVIRA#658#elvira.cordioli#sender.at#SI
I'd like to have
response.write rs.fields(0) 'CRDLVR47E67L781V
response.write rs.fields(5) 'elvira.cordioli#sender.at
While I can't rule out that there is some version of OLEDB that does HTTP or accepts FMT and FORMAT in the connection string, I'm sure that the Data Source property of an ADODB Text connection needs to be a folder.
Instead of trying to specify a global separator in the connection string or the in the registry, I'd use a schema.ini file to describe the meta info in a file specific way.
All in one:
cscript 41224005.vbs
.\41224005.vbs
Option Explicit
Dim oFS : Set oFS = CreateObject("Scripting.FileSystemObject")
Dim sF
For Each sF In Split(".\41224005.vbs ..\data\schema.ini ..\data\data1.txt")
WScript.Echo sF
WScript.Echo oFS.OpenTextFile(sF).ReadAll()
WScript.Echo "---------------"
Next
Dim sDir : sDir = oFS.GetAbsolutePathName("..\data\")
Dim sCS : sCS = Join(Array( _
"Provider=Microsoft.Jet.OLEDB.4.0" _
, "Data Source=" & sDir _
, "Extended Properties='" & Join(Array( _
"text" _
), ";") & "'" _
), ";")
Dim oDb : Set oDb = CreateObject("ADODB.Connection")
oDb.Open sCS
'WScript.Echo oDb.ConnectionString
Dim oRS : Set oRS = oDb.Execute("SELECT * FROM [data1.txt]")
WScript.Echo oRS.Fields(0).Value
WScript.Echo oRS.Fields(6).Value
oRS.Close
oDb.Close
---------------
..\data\schema.ini
[data1.txt]
FORMAT=Delimited(#)
ColNameHeader=False
---------------
..\data\data1.txt
CRDLVR47E67L781V#1653#CORDIOLI#ELVIRA#658#elvira.cordioli#sender.at#SI
---------------
CRDLVR47E67L781V
SI
Related
I am trying to create VBscript to export process data from a SCADA system (WinCC RT Professional) to periodically archive all process variables. The data are stored in SQL table that can be accessed through a connectivity pack. I managed to make the script working when exporting one tag (process variable), but I would like to loop over all tags in the system (about 60), collect them in another recordset and then all data from this recordset save in one csv-file. I have created RecSet that collects all variables (fields) of one tag (Time, Process Variable etc.), I only need values from Field 4 (the same field for all tags). I would then like to copy this field in another recordset - RecSetColl which collects all required data (Field 4) from all tags and finally save them in the CSV file. Thank you very much for any help.
Sub DataExport()
Dim fso 'FileSystemObject
Dim f 'File
Dim ts 'TextStream
Dim path 'Path
Dim ArchiveDate 'Archive date
'Name of CSV-file
ArchiveDate = ArchiveDate & Now
ArchiveDate = Replace(ArchiveDate,"/","")
ArchiveDate = Replace(ArchiveDate," ","")
ArchiveDate = Replace(ArchiveDate,":","")
ArchiveDate = "MDF_" & ArchiveDate
'Path to the csv-file
path = "D:\Historical_data\" & ArchiveDate & ".csv"
'Create Filesystemobject and CSV-file if not exists:
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FileExists(path) Then
fso.CreateTextFile(path)
Else
MsgBox "File already exists!"
Exit Sub
End If
'Create object and open it for writing
Set f = fso.GetFile(path)
Set ts = f.OpenAsTextStream(2,-2)
ts.WriteLine("Tag-Name;ValueID;Date/Time;Process-Value") 'Header
'Generate String for the CSV-Filename
Dim Pro 'Provider
Dim DSN 'Data Source Name
Dim DS 'Data Source
Dim ConnString 'Connection String
Dim MachineNameRT 'Name of the PC from WinCC-RT
Dim DSNRT 'Data Source Name from WinnCC-RT
Dim Conn 'Connection to ADODB
Dim RecSet 'RecordSet
Dim RecSetColl 'RecordSet storing data to be saved to the CSV-file
Dim Command 'Query
Dim CommandText 'Command-Text
Dim i
'Read the name of the PC-Station and the DSN-Name from WinCC-RT
Set MachineNameRT = HMIRuntime.Tags("#LocalMachineName")
Set DSNRT = HMIRuntime.Tags("#DatasourceNameRT")
'Preparing the Connection-String
Pro = "Provider=WinCCOLEDBProvider.1;" 'First instance of WinCCOLEDB
DSN = "Catalog=" & DSNRT.Read & ";" 'Name of Runtime-Database
DS = "Data Source=" & MachineNameRT.Read & "\WinCC" 'Data Source
'Build the complete String:
ConnString = Pro + DSN + DS
'Make Connection
Set Conn = CreateObject("ADODB.Connection")
Conn.ConnectionString = ConnString
Conn.CursorLocation = 3
Conn.open
Set RecSetColl = CreateObject("ADODB.Recordset")
With RecSetColl.Fields
.Append "Time1", adChar
.Append "AHU_RUN", adChar
.Append "Time2", adChar
.Append "TT01", adChar
.Append "TT02", adChar
End With
For i = 0 To 4
Set RecSet = CreateObject("ADODB.Recordset")
Set Command = CreateObject("ADODB.Command")
Command.CommandType = 1
Set Command.ActiveConnection = Conn
'Building the complete string
CommandText = "Tag:R," & i & ",'0000-00-00 12:00:00.000','0000-00-00 00:00:00.000'"
Command.CommandText = CommandText
Set RecSet = Command.Execute
RecSet.MoveFirst
RecSetColl.Fields(i) = RecSet.Fields(4) 'RecSet.Fields(4) stores a proces value
RecSet.Close
Set RecSet = Nothing
Set Command = Nothing
Next
'Writing recordsets to CSV-file
Do While Not RecSetColl.EOF
ts.WriteLine (RecSetColl.Fields(0).Value & ";" & RecSetColl.Fields(1).Value & ";" & RecSetColl.Fields(2).Value & ";" & RecSetColl.Fields(3).Value & ";" & RecSetColl.Fields(4).Value & ";" & RecSetColl.Fields(5).Value)
RecSetColl.MoveNext
Loop
RecSetColl.Close
Set RecSetColl = Nothing
Conn.close
Set Conn = Nothing
ts.Close
Set fso = Nothing
Set f = Nothing
Set ts = Nothing
End Sub
I do not really know whats not working, but a guess;
Does ValueID = 0 , (the "i" in the "for 0 to 4" ) exist in your project?
In the table "Archive" you will find the valid ValueIDs, starts with "1" in all my projects. It's simple to see in SQL Management Studio, perhaps sometimes 0 exist.
To get all the values exported, query the "Archive" table first and then ask for data in a loop using whatever ValueID's is returned.
//PerD
I want to be able to view the contents of my access database's laccdb file through VBA so I can use it to alert users (through a button) who else is in the database.
I specifically don't want to use a 3rd Party tool. I have tried using:
Set ts = fso.OpenTextFile(strFile, ForReading)
strContents = ts.ReadAll
This works fine if only 1 user is in the database. But for multiple users it gets confused by the presumably non-ASCII characters and goes into this kind of thing after one entry:
Does anyone have any suggestions? It's fine if I just open the file in Notepad++...
Code eventually used is as follows (I didn't need the title and have removed some code not being used):
Sub ShowUserRosterMultipleUsers()
Dim cn As New ADODB.Connection, rs As New ADODB.Recordset
cn.Provider = "Microsoft.ACE.OLEDB.12.0"
cn.Open "Data Source=" & CurrentDb.Name
Set rs = cn.OpenSchema(adSchemaProviderSpecific, , "{947bb102-5d43-11d1-bdbf-00c04fb92675}")
While Not rs.EOF
Debug.Print rs.Fields(0)
rs.MoveNext
Wend
End Sub
I found this which should help, it's not actually reading the ldb file, but it has the info that you need (Source: https://support.microsoft.com/en-us/kb/198755):
Sub ShowUserRosterMultipleUsers()
Dim cn As New ADODB.Connection
Dim cn2 As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim i, j As Long
cn.Provider = "Microsoft.Jet.OLEDB.4.0"
cn.Open "Data Source=c:\Northwind.mdb"
cn2.Open "Provider=Microsoft.Jet.OLEDB.4.0;" _
& "Data Source=c:\Northwind.mdb"
' The user roster is exposed as a provider-specific schema rowset
' in the Jet 4 OLE DB provider. You have to use a GUID to
' reference the schema, as provider-specific schemas are not
' listed in ADO's type library for schema rowsets
Set rs = cn.OpenSchema(adSchemaProviderSpecific, _
, "{947bb102-5d43-11d1-bdbf-00c04fb92675}")
'Output the list of all users in the current database.
Debug.Print rs.Fields(0).Name, "", rs.Fields(1).Name, _
"", rs.Fields(2).Name, rs.Fields(3).Name
While Not rs.EOF
Debug.Print rs.Fields(0), rs.Fields(1), _
rs.Fields(2), rs.Fields(3)
rs.MoveNext
Wend
End Sub
I put together some code to read through the lock file and output a message listing users currently using the system.
Trying to read the whole file in at once seems to result in VBA treating the string as Unicode in the same way notepad does so I read in character by character and filter out non printing characters.
Sub TestOpenLaccdb()
Dim stm As TextStream, fso As FileSystemObject, strLine As String, strChar As String, strArr() As String, nArr As Long, nArrMax As Long, nArrMin As Long
Dim strFilename As String, strMessage As String
strFilename = CurrentProject.FullName
strFilename = Left(strFilename, InStrRev(strFilename, ".")) & "laccdb"
Set fso = New FileSystemObject
Set stm = fso.OpenTextFile(strFilename, ForReading, False, TristateFalse) 'open the file as a textstream using the filesystem object (add ref to Microsoft Scripting Runtime)
While Not stm.AtEndOfStream 'Read through the file one character at a time
strChar = stm.Read(1)
If Asc(strChar) > 13 And Asc(strChar) < 127 Then 'Filter out the nulls and other non printing characters
strLine = strLine & strChar
End If
Wend
strMessage = "Users Logged In: " & vbCrLf
'Debug.Print strLine
strArr = Split(strLine, "Admin", , vbTextCompare) 'Because everyone logs in as admin user split using the string "Admin"
nArrMax = UBound(strArr)
nArrMin = LBound(strArr)
For nArr = nArrMin To nArrMax 'Loop through all machine numbers in lock file
strArr(nArr) = Trim(strArr(nArr)) 'Strip leading and trailing spaces
If Len(strArr(nArr)) > 1 Then 'skip blank value at end
'Because I log when a user opens the database with username and machine name I can look it up in the event log
strMessage = strMessage & DLast("EventDescription", "tblEventLog", "[EventDescription] like ""*" & strArr(nArr) & "*""") & vbCrLf
End If
Next
MsgBox strMessage 'let the user know who is logged in
stm.Close
Set stm = Nothing
Set fso = Nothing
End Sub
I have a couple tables that are connected to an access database through Microsoft Query. If I move the location of the access file or I need a way to update the source location especially since I will need to share this file with other people.
All the connections are ODBC and are from the same access file.
Since all the connection are uniform I looped through each one and replaced the current source file with the file selected through the windows file explorer.
Sub SwitchODBCSource()
Dim conn As WorkbookConnection
Dim sOldConnection As String, sNewConnection As String
getfilePath = Application.GetOpenFilename()
FileType = ".accdb"
If InStr(getfilePath, FileType) Then
fileName = Dir(getfilePath)
filePath = Replace(getfilePath, "\" & fileName, "")
For Each conn In ActiveWorkbook.Connections
With conn
conn.ODBCConnection.BackgroundQuery = False
conn.ODBCConnection.CommandType = xlCmdSql
conn.ODBCConnection.Connection = Array(Array( _
"ODBC;DSN=MS Access Database;DBQ=" & filePath & "\" & fileName & ";DefaultDir=" _
), Array( _
filePath & ";DriverId=25;FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;" _
))
End With
Next conn
ActiveWorkbook.RefreshAll
Call Sheet1.dropDown
Set conn = Nothing
Else
MsgBox ("Can only use " & FileType & " files")
End If
End Sub
I'm trying to use a script I found on the internet to allow the bulk creation of new user accounts in Active Directory using VBScript and a CSV file. I'm not using CSVDE b/c this script will also create passwords. I keep encountering this error when running the code I cannot figure it out. Can anyone help?
'*********************************************************************
' Script: createUsersFromCSV.vbs *
' Creates new user accounts in Active Directory from a CSV file. *
' Input: CSV file with layout logonname,firstname,lastname,password *
' *
'*********************************************************************
Option Explicit
Dim sCSVFileLocation
Dim sCSVFile
Dim oConnection
Dim oRecordSet
Dim oNewUser
' Variables needed for LDAP connection
Dim oRootLDAP
Dim oContainer
' Holding variables for information import from CSV file
Dim sLogon
Dim sFirstName
Dim sLastName
Dim sDisplayName
Dim sPassword
Dim nPwdLastSet
Dim nUserAccountControl ' Used to enable the account
Dim sDomain
Dim sCompany
Dim sPhone
Dim sEmail
Dim sDescription
Dim NumChar, Count, strRdm, intRdm
Dim fso, f, fso1, f1
'* Modify this to match your company's AD domain
sDomain="mydomain.local"
'* Input file location
sCSVFileLocation = "C:\Documents and Settings\Administrator\Desktop\" 'KEEP TRAILING SLASH!
'* Full path to input file
sCSVFile = sCSVFileLocation&"newusers.csv"
' Commands used to open the CSV file and select all of the records
set oConnection = createobject("adodb.connection")
set oRecordSet = createobject("adodb.recordset")
oConnection.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source= " & _
sCSVFileLocation & ";Extended Properties=""text;HDR=NO;FMT=Delimited"""
oRecordSet.open "SELECT * FROM " & sCSVFile ,oConnection
' Create a connection to an Active Directory OU container.
Set oRootLDAP = GetObject("LDAP://rootDSE")
Set oContainer = GetObject("LDAP://ou=Test," & _
oRootLDAP.Get("defaultNamingContext"))
on error resume next
do until oRecordSet.EOF ' Reads the values (cells) in the sInputFile file.
' --------- Start creating user account
' Read variable information from the CSV file
' and build everything needed to create the account
sLogon = oRecordSet.Fields.Item(0).value
sFirstName = oRecordSet.Fields.Item(1).value
sLastName = oRecordSet.Fields.Item(2).value
sDisplayName = sFirstName&" "&sLastName
sPassword = oRecordSet.Fields.Item(3).value
' Build the User account
Set oNewUser = oContainer.Create("User","cn="&sFirstName&" "&sLastName)
oNewUser.put "sAMAccountName",lcase(sLogon)
oNewUser.put "givenName",sFirstName
oNewUser.put "sn",sLastName
oNewUser.put "UserPrincipalName",lcase(SLogon)&"#"&sDomain
oNewUser.put "DisplayName",sDisplayName
oNewUser.put "name",lcase(sLogon)
' Write this information into Active Directory so we can
' modify the password and enable the user account
oNewUser.SetInfo
' Change the users password
oNewUser.SetPassword sPassword
oNewUser.Put "pwdLastSet", 0
' Enable the user account
oNewUser.Put "userAccountControl", 512
oNewUser.SetInfo
objFile.Close
'*******************
oRecordset.MoveNext
Loop
'*******************
' Used only for debugging
'if err.number = -2147019886 then
' msgbox "User logon " & sLogon & "already exists"
'End If
' --------- End of user account creation
Here is where the error is occuring, line 51 char 1:
oRecordSet.open "SELECT * FROM " & sCSVFile ,oConnection
Maybe sCSVFile contains special characters and therefore must be escaped like this:
oRecordSet.open "SELECT * FROM [" & sCSVFile & "]", oConnection
I hope it helps.
I have an Access database which I would like to export to a text file. I have a schema defined within Access, and currently use a macro to export it. I would like to use VBScript to always append the result of a query to the same file. If it is not possible to use my defined schema, I only need the fields to be comma separated and enclosed by the ", and the text file must be in UTF-8 format.
I found the following code snippet, but I am unsure how to adopt it for my needs.
db = "C:\Docs\LTD.mdb"
TextExportFile = "C:\Docs\Exp.txt"
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
strSQL = "SELECT * FROM tblMembers"
rs.Open strSQL, cn, 3, 3
Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.CreateTextFile(TextExportFile, True)
a = rs.GetString
f.WriteLine a
f.Close
DIRECTION (2)
This is some VBA, run from the Access database:
Sub InsertRecs()
Set db = CurrentDb
'DSN=Suitable system DSN for MySQL
'Then, depending on your set up, you can incude:
'Database=DBName;
'Trusted_Connection=Yes;
'NameOfMySQLTable
strSQL = "INSERT INTO [ODBC;DSN=baywotch;].tblAuction Select * FROM tblAuction;"
db.Execute strSQL, dbFailOnError
End Sub
This is the same thing, but in VBScript, using DAO:
Dim objEngine
Dim objWS
Dim objDB
Dim db: db = "C:\Docs\baywotch.db5"
Set objEngine = wscript.CreateObject("DAO.DBEngine.36")
Set objDB = objEngine.OpenDatabase(db)
objDB.Execute "INSERT INTO [ODBC;DSN=baywotch].[tblAuction] SELECT * FROM tblAuction;"
DIRECTION (1)
I suggest a completely different direction, and that is to let MySQL do the work:
MySQL Migration Toolkit
I tested this against your database, and it appears to import correctly, only takes a few minutes, and will generate all sorts of reusable scripts and so on.
If you are having problems with the set-up of MySQL, you may wish to read:
9.1.4. Connection Character Sets and Collations
DiRECTION (0)
REWRITE (2)
'========================================================================'
'
' FROM: AnthonyWJones, see post '
'
'========================================================================'
Dim db: db = "C:\Docs\baywotch.db5"
Dim exportDir: exportDir = "C:\Docs\" '" SO prettify does not do VB well
Dim exportFile: exportFile=NewFileName(exportDir)
Dim cn: Set cn = CreateObject("ADODB.Connection")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
cn.Execute "SELECT * INTO [text;HDR=Yes;Database=" & exportDir & _
";CharacterSet=65001]." & exportFile & " FROM tblAuction"
'Export file
'========================================================================'
'Support functions
Function NewFileName(ExportPath)
Dim fs
Dim NewFileTemp
Set fs = CreateObject("Scripting.FileSystemObject")
NewFileTemp = "CSV" & Year(Date) _
& Right("00" & Month(Date),2) & Right("00" & Day(Date) ,2) & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = 1
Do While a
NewFileTemp = "CSV" & Year(Date) _
& Right("00" & Month(Date),2) & Right("00" & Day(Date) ,2) & "_" & i & ".csv"
a = fs.FileExists(ExportPath & NewFileTemp)
i = i + 1
If i > 9 Then
'Nine seems enough times per day to be
'exporting a table
a = True
MsgBox "Too many attempts"
WScript.Quit
End If
Loop
NewFileName = NewFileTemp
End Function
Perhaps the easiest way is to use [text...].filename approach:-
Dim db: db = "C:\Docs\LTD.mdb"
Dim exportDir: exportDir = "C:\Docs\" '" SO prettify does not do VB well
Dim exportFile: exportFile = "Exp.txt"
Dim cn: Set cn = CreateObject("ADODB.Connection")
cn.Open _
"Provider = Microsoft.Jet.OLEDB.4.0; " & _
"Data Source =" & db
cn.Execute "SELECT * INTO [text;HDR=Yes;Database=" & exportDir & _
";CharacterSet=65001]." & exportFile & " FROM tblMembers"
FileSystemObject won't help you since it doesn't do UTF-8. UTF-8 is acheived by specifying CharacterSet=65001 (65001 is the UTF-8 codepage). Note the file generated does not contain a UTF-8 BOM but the schema.ini file created will note that the CharacterSet is UTF-8.
Note this doesn't achieve your append requirements are you sure that makes sense anyway, won't you end up with lots of duplicates?
Edit:
The above is adjusted to include the UTF-8 requirement. You can simply append something like the date to create multiple snapshot files for the table.
I've numbered the lines for reference.
1. db = "C:\Docs\LTD.mdb"
2. TextExportFile = "C:\Docs\Exp.txt"
3. strSQL = "SELECT * FROM tblMembers"
4. Set f = fs.CreateTextFile(TextExportFile, True)
Line 1 - is the current access database file you are working with. this case it's LTD.mdb
Line 2 - is the name of the file that you are going to write/append. It's Exp.txt
Line 3 - is the sql statement that will be used to collect the data.
Line 4 - is the command to open the file to write to.
Change line 2 to the name of file you want.
Change line 3 to the table you want to use. Select * will use all the columns if you want only a couple identify them by name. select col1, col2 ... from mytable. You will want to look into using where clauses also.
Change line 4 from CreateTextFile to OpenTextFile and use ForAppending to append.
MSDN VBA
I'm drawing a blank on formatting the line. One of the ways I use is modify the select statement to include commas. example select col1 & "," & col2 from mytable.
For UTF-8 (I don't have a working example) Try:
utf = new String(a, 0, a.length, UTF-8);
f.WriteLine utf;
UTF-8 VBA
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adClipString = 2
Const ForWriting = 2
Const ForAppending = 8
Const strDB = "C:\Docs\LTD.mdb"
Const strCSV = "C:\Docs\Exp.csv"
Set objAccessConnection = CreateObject("ADODB.Connection")
objAccessConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Data Source=" & strDB
Set objAccessRecordset = CreateObject("ADODB.Recordset")
strAccessQuery = "SELECT * FROM tblMembers"
objAccessRecordset.Open strAccessQuery, objAccessConnection, adOpenStatic, adLockOptimistic
Set objCSV = CreateObject("Scripting.FileSystemObject").OpenTextFile(strCSV, ForAppending, True)
objCSV.Write objAccessRecordset.GetString(adClipString,,",",CRLF)
objCSV.Close
Set objCSV = Nothing
objAccessRecordset.Close
Set objAccessRecordset = Nothing
objAccessConnection.Close
Set objAccessConnection = Nothing