Strange characters in string when importing sql file via VBA - sql

I'm trying to import an SQL file into excel via VBA in order to return the SQL code as one string, however I'm getting tiny squares (carriage returns?) between each character when I import the SQL as a string - not a clue why! It's worked before in other files, with different SQL, so I'm not sure what I've done wrong.
Function ImportSQLText(FileExt, FileSQLName)
'//Needs Microsoft Scripting Runtime Ref
'//and microsoft active x data objects 2.8
Dim ReadText As String, newLine As String
Dim fso As FileSystemObject: Set fso = New FileSystemObject
Set txtStream = fso.OpenTextFile(FileExt & fileName, ForReading, False)
ReadText = " "
Do While Not txtStream.AtEndOfStream
newLine = txtStream.ReadLine
If InStr(newLine, "[input-sDte]") > 0 Then
ReadText = ReadText & Replace(newLine, "[input-sDte]", sDte) & vbCrLf
ElseIf InStr(newLine, "[input-eDte]") > 0 Then
ReadText = ReadText & Replace(newLine, "[input-eDte]", eDte) & vbCrLf
Else
ReadText = ReadText & newLine & vbCrLf
End If
Loop
txtStream.Close
ImportSQLText = ReadText
End Function
The SQL code looks like:
;if object_id('tempdb.#usr_fld') is not null
drop table #usr_fld
-- Creating Temp Table
CREATE TABLE #usr_fld([PLACE-REF] NVARCHAR(50)
,[PROJCODE] nvarchar(100)
,[CUORACLE] nvarchar(100));
Any input would be greatly appreciated - googling it is not helping me this time.

You almost definitely have a unicode file. There is an optional fourth parameter on the OpenTextfile method of FSO:
Const TriStateTrue = -1
Set txtStream = fso.OpenTextFile(FileExt & fileName, ForReading, False, TriStateTrue)
Just swap out your line for these two and it might fix the issue.

Related

Read message from text file and display in message box in vb.net

JavaError.128 = "project creation failed. & vbLf & Please try again and if the problem persists then contact the administrator"
I am able to read this message from text file. the issue is vbLf is not considered as newline in msgbox. it prints vbLf in msgbox.
Using sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(errorfilePath)
While ((sr.Peek() <> -1))
line = sr.ReadLine
If line.Trim().StartsWith("JavaError." & output) Then
isValueFound = True
Exit While
End If
End While
sr.Close()
End Using
If isValueFound Then
Dim strArray As String() = line.Split("="c)
MsgBox(strArray(1).Replace("""", "").Trim({" "c}))
End If
You can make all your code a simpler one line version using File.ReadAllLines and LINQ. This code will put all the lines starting with javaerror into the textbox, not just the first:
textBox.Lines = File.ReadAllLines(errorFilePath) _
.Where(Function(s) s.Trim().StartsWith("JavaError")) _
.Select(Function(t) t.Substring(t.IndexOf("= ") + 2).Replace(" & vbLf & ", Environment.NewLine)) _
.ToArray()
You need to Imports System.IO and System.Linq
This code reads all the lines of the file into an array, then uses LINQ to pull out only those starting with java error, then projects a new string of everything after the = with vbLf replaced with a newline, converts the enumerable projection to an array of strings and assigns it to the textBox lines
If you don't want all the lines but instead only the first:
textBox.Text = File.ReadLines(errorFilePath) _
.FirstOrDefault(Function(s) s.Trim().StartsWith("JavaError")) _
?.Substring(t.IndexOf("= ") + 2).Replace(" & vbLf & ", Environment.NewLine))
This one uses ReadLine instead of ReadALlLines - ReadLines works progressively, and it makes sense to be able to stop reading after we foundt he first rather than have the overhead of reading ALL (million) lines only to then end up pulling the first out and throwing 999,999 lines of effort away. So it's reading line by line, pulls out the first that starts with "JavaError" (or Nothing if there is no such line), then checks if Nothing came out (the ?) and skips the Substring if it was Nothing, or it does a Substring on everything after the = and replaces vbLf with newline
For a straight up mod of your original code:
Using sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(errorfilePath)
While ((sr.Peek() <> -1))
line = sr.ReadLine
If line.Trim().StartsWith("JavaError." & output) Then
isValueFound = True
line = line.Replace(" & vbLf & ", Environment.NewLine))
'^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ added code
Exit While
End If
End While
sr.Close()
End Using
If isValueFound Then
Dim strArray As String() = line.Split("="c)
MsgBox(strArray(1).Replace("""", "").Trim({" "c}))
End If
Note that I've always made my replacement on & vbLf & with a space at each end to avoid stray spaces being left behind - if your file sometimes doesn't have them, consider using Regex to do the replace, e.g. Regex.Replace(line, " ?& vbLf & ?", Environment.NewLine
This could work:
Dim txtFile As String = "project creation failed. & vbLf & Please try again and if the problem persists then contact the administrator"
Dim arraytext() As String = txtFile.Split("&")
Dim txtMsgBox As String = Nothing
For Each row As String In arraytext
If Trim(row) = "vbLf" Then
txtMsgBox = txtMsgBox & vbLf
Else
txtMsgBox = txtMsgBox & Trim(row)
End If
Next
MsgBox(txtMsgBox)

MS access. VBA. exporting reuslts from two tables to a text file using semicolon as delimiter

I'm New to this forum so please be patient with me, thanks. I am not an expert in VBA. I am from Norway so my english is not the best.
I need to create a text-file generator. The text-files are beeing used as inspection reports in a pipe inspection program.
The text-file must look like this.
[Inspection1]
PipeID=112
FromPointNo=8696
ToPointNo=8292
Street=Trykkeriveien
Date=30.07.2009
Signature=Tho
Weather=B
PreWashed=N
ArchiveRef=
PipeFeature=AF
Material=Bet
Dimension=400
PipeForm=S
VerticalDim=
PipeLength=94,24
Comment= SM=9,6
SD=0
Obs=Distance;Observation;Type;ClockPos;Rank;Photo;VideoPos;Comment
Obs1=0,00;SI;;;0;No;;Start inspection
Obs2=4,38;PC;;0;1;No;;Pipe connection, from 01-12
Obs3=11,55;PC;;2;2;No;;Pipe connection, from 00-11
Obs4=21,21;PC;;1;1;No;;Pipe connection, from 02-12
Obs5=22,56;FI;;;0;No;;Inspection finished
For solving this i have created two tables, one for the inspection and the other for the inspection details.
The difficult part is how to deal with the header (the upper part of the text-file) and the details below.
I have a built up a string that contains the header and it looks exactely like it should. BUT!!! The lower part (the part containing the oberservation details)
I have not solved. I have tried several approaches, but have not suceeded - YET.
Any suggestion on how to proceed?
Best Regards from Anders
This sounds like a job for ADODB.Recordset.GetString!!! This method will wrap field and record values using ColumnDelimiter and RowDelimiter respectively. It allows for fast creation of csv file and even HTML tables.
MSDN - GetString Method (ADO)
Variant = recordset.GetString(StringFormat, NumRows, ColumnDelimiter, RowDelimiter, NullExpr)
test.txt
test.html
Sub TestFile()
Const FILEPATH = "C:\Users\Owner\Documents\stack-overflow\Inspection Reports\test.txt"
Dim OutputString As String
OutputString = getInspectionDetails & vbCrLf & vbCrLf & vbCrLf & getInspection
Open FILEPATH For Output As #1
Print #1, OutputString
Close #1
End Sub
Function getInspection(Optional ColumnDelimeter = ";", Optional RowDelimeter = vbCrLf) As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "[Inspection]", CurrentProject.Connection
'RowDelimeter
getInspection = rs.GetString(ColumnDelimeter:=ColumnDelimeter, RowDelimeter:=RowDelimeter, NullExpr:=" ")
rs.Close
Set rs = Nothing
End Function
Function getInspectionDetails(Optional ColumnDelimeter = ";", Optional RowDelimeter = vbCrLf) As String
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open "[Inspection Details]", CurrentProject.Connection
getInspectionDetails = rs.GetString(ColumnDelimeter:=ColumnDelimeter, RowDelimeter:=RowDelimeter, NullExpr:=" ")
rs.Close
Set rs = Nothing
End Function
Sub TestHTML()
Const FILEPATH = "C:\Users\Owner\Documents\stack-overflow\Inspection Reports\test.html"
Dim OutputString As String, tBody As String
OutputString = "<!DOCTYPE html><body><table>#tablebody</table></body></html>"
tBody = getInspection(getInspection("</td><td>", "</td></tr>" & vbCrLf & "<tr><td>"))
tBody = "<tr>" & Left(tBody, Len(tBody) - 4)
Open FILEPATH For Output As #1
Print #1, Replace(OutputString, "#tablebody", tBody)
Close #1
End Sub

vb.net Splitting string lines into new strings

I want to split a string - which includes multiple lines - into new strings.
As it seems that people dont understand my problem here some further informations:
I read out values into strings from a XML-file. Some of those strings countain multiple lines. Now I need every single value of that string on a new string(variable) so that I can tell Homer to drink a beer and tell Lenny to go to bed and not tell the whole Team to go to bed. (Hopefully this story helps you :D )
To keep this simple I'll define a "static" string for this sample.
I'll put 3 of my tries down below. I'd love to hear what's wrong with them. I also tried it with lists and enums where I could split the string but no define a new one..
But I assume that there is a much easier solution for my problem...
Dim team As String = "Simpson, Homer" & vbCrLf & "Leonard, Lenny" & vbCrLf & "Carlson, Carl"
1.
Dim objReader As New StringReader(team)
Dim tm() As String
Dim i As Integer = 1
Do While objReader.Peek() <> -1
tm(i) = objReader.ReadLine() & vbNewLine
i = i + 1
Loop
Dim i As Integer = 0
For Each Line As String In team.Split(New [Char]() {CChar(vbTab)})
Dim tm(i) As String = ReadLine(team, i)
i = i + 1
Next
3.
Dim tm() As String
Dim i As Integer = 0
Dim objReader As New StringReader(team)
Do While objReader.Peek() <> -1
tm(i) = ReadLine(team, i)
i = i + 1
Loop
And the function used in 2. and 3.
Public Function ReadLine(ByVal sFile As String, Optional ByVal nLine As Long = 1) As String
Dim sLines() As String
Dim oFSO As Object
Dim oFile As Object
On Error GoTo ErrHandler
oFSO = CreateObject("Scripting.FileSystemObject")
If oFSO.FileExists(sFile) Then
oFile = oFSO.OpenTextFile(sFile)
sLines = Split(oFile.ReadAll, vbCrLf)
oFile.Close()
Select Case Math.Sign(nLine)
Case 1
ReadLine = sLines(nLine - 1)
Case -1
ReadLine = sLines(UBound(sLines) + nLine + 1)
End Select
End If
ErrHandler:
oFile = Nothing
oFSO = Nothing
End Function
Thanks in advance for any shared thoughts.
There is in fact an easy solution for my problem. Sorry if I caused confusion.
Module Module1
Dim team As String = "Simpson, Homer" & vbCrLf & "Leonard, Lenny" & vbCrLf & "Carlson, Carl"
Sub Main()
Dim tm As String() = team.Split(vbLf)
'Test
Console.WriteLine(tm(0)) 'Homer
Console.WriteLine(tm(1)) 'Lenny
Console.WriteLine(tm(2)) 'Carl
End Sub
End Module

VBNet Reading csv file - separating column in a row - comma delimited

This has been bugging me for a week and i do not see any other way. We have only been taught record data structures which is basic, FileOpen, WriteLine and etc. but i read MSDN and StreamWriter/Reader looks much more promising. This is an assignment/coursework and its essential for practically all parts of the program.
All i want to do is read line by line separating fields by a comma and define it as a variable. It would also help to be able to read the line without the quotes "", because right now when i read a password out with LineInput it reads it entirely "pass".
Private Sub StudentLogin()
Dim Filename As New StreamWriter("" & Register.StudentDirectory & "" & Username & ".txt")
Dim str As String = "This"
Dim lines() As String = str.Split(New String() {Environment.NewLine}, StringSplitOptions.None)
For Each line As String In lines
Dim columns() As String = line.Split(","c)
Firstname = columns(0)
Surname = columns(1)
Password = columns(2)
ClassID = columns(3)
Next
MessageBox.Show("" & ClassID & " " & Password & "")
End Sub
Text file:
"cem","polat","pass","class"
I just want to read the file - then each line, row by row, defining each column field which is in C:/Spellcheck/data/accounts/students/+filename+ and define a few variables.

Find and replace running in a never ending loop

I am currently using this code snippet in my script for replacing text in an ASCII file
Dim fso, inputFile, outputFile
Dim str As String
Const quote As String = """"
Dim MyFile As String = Folder & "\client-1\com\company\assembleegameclient\parameters\Parameters.class.asasm"
fso = CreateObject("Scripting.FileSystemObject")
inputFile = fso.OpenTextFile(MyFile, 1)
str = inputFile.ReadAll
str = Replace(str, quote & TextBox1.Text & quote, quote & TextBox3.Text & quote)
outputFile = fso.CreateTextFile(MyFile, True)
outputFile.Write(str)
System.Threading.Thread.Sleep(5000)
I put the threading at the end of the to see if it would fix the problem by waiting, but it doesn't work. The next step in the script requires this portion to be completely finished before proceeding. Is there a way to attach this to a process with waitforexit? or something similar that works on strings?
It would be optimal if it would output the number of changes that were made and that it was complete.