So, I'm using the output from a record set and writing out to a csv file. But I'm getting an issue with Quotation marks. Ideally I'd like to include them as text markers. But if I include them in my line of text they get printed as two sets of quotation marks.
I want this as the output (delimited by tabs):
"Header1" "header2" "......[]...."headerX"
I tried this
Sub Write_Tbl(Filename, StrSQL)
Dim unicode, UTF, i As Long , Fileout As Object, forwriting, TristateUseDefault, TxtStr As String, TextHolder As String, rs As Recordset
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Dim File_out As Object
Set File_out = fso.CreateTextFile(Filename, True, unicode = UTF - 8)
File_out.Close
Open Filename For Output As #1
Set rs = CurrentDb.OpenRecordset(StrSQL)
rs.MoveFirst
'for headers
TxtStr = rs.Fields.Item(0).Name 'so that there isn't a tab at the start of the string
For i = 1 To rs.Fields.Count - 1
TxtStr = TxtStr & chr(34) & vbTab & chr(34) & rs.Fields.Item(i).Name
Next i
Write #1, TxtStr & chr(34) 'write headers to file
and got this as the output
""Header1"" ""header2"" ""......[]....""headerX""
So I removed the quotation marks and got this:
'for headers
TxtStr = rs.Fields.Item(0).Name 'so that there isn't a tab at the start of the string
For i = 1 To rs.Fields.Count - 1
TxtStr = TxtStr & vbTab & rs.Fields.Item(i).Name
Next i
Write #1, TxtStr 'write headers to file
and what I'm getting is
"Header1 header2 ......[]....headerX"
If I monitor the variables in the locals window, there's only one set of quotes so it must be something to do with printing? It doesn't happen if I use single quotation marks (ascii no 39). I also tried just using write to file, rather than as a text stream, but I got memory issues and ERROR 5 issues. STUMPED. Please help.
If you have prepared your text string in VBA, you should use the Print # statement instead of Write # .
Documentation: Print # vs. Write #
Unlike the Print # statement, the Write # statement inserts commas between items and quotation marks around strings as they are written to the file.
Note:
I'm not sure if these functions write Unicode at all, or care how the file was created.
Open Filename For Output As #1
will create the file if it doesn't exist, so you can probably omit the whole CreateTextFile part.
Or use File_out.WriteLine() instead, it seems odd to mix both methods (FSO and the ancient Print/Write statements).
Edit: see How to create and write to a txt file using VBA
Related
It is easy to find in the internet a way of write into a txt file but all I find is always writing in the very last line:
Sub write_log(sentence_to_be_written As String)
Dim strFile_Path As String
strFile_Path = "C:\Users\[user_name]\Desktop\log.txt"
Open strFile_Path For Append As #1
Print #1, Now() & " --> " & sentence_to_be_written
Close #1
End Sub
I would like to write instead into the first line of the txt file.
Try the next code, please. It needs a reference to Microsoft Scripting Runtime. It can be adapted to work without such a reference. In fact, I will also post a pice of code able to automatically add the necessary reference... It is possible to read the text using standard VBA Open, but only concatenating line by line and I think this solution is more elegant:
Sub write_log_OnTop(sentence_to_be_written As String)
'It neds a reference to 'Microsoft Script Runtime'
Dim strFile_Path As String, strText As String
Dim fso As New FileSystemObject, txtStr As TextStream
strFile_Path = "C:\Users\Fane Branesti\OneDrive\Desktop\log.txt"
If Dir(strFile_Path) <> "" Then 'check if file exists
Set txtStr = fso.OpenTextFile(strFile_Path)
strText = txtStr.ReadAll
txtStr.Close
Else
MsgBox "Wrong file path...": Exit Sub
End If
strText = Now() & " --> " & sentence_to_be_written & vbCrLf & strText
Open strFile_Path For Output As #1
Print #1, strText
Close #1
End Sub
And Microsoft Scripting Runtime reference can be automatically add by running of the next code:
Private Sub Add_Scripting_Reference() 'Adds 'Microsoft Scripting Runtime'
Dim wb As Workbook, r As Reference
Set wb = ThisWorkbook
For Each r In wb.VBProject.References
If r.name = "Scripting" Then Exit Sub
Next
wb.VBProject.References.AddFromFile Environ("windir") & "\system32\scrrun.dll"
End Sub
If you do not want the reference, even if I would not understand such a choice, it is enough to comment/replace the code line
Dim fso As New FileSystemObject, txtStr As TextStream
with:
Dim fso As Object, txtStr As Object: Set fso = CreateObject("Scripting.FileSystemObject")
There is no command to add text at the top (or the middle) of any file. I never heard about such command in any programming language. It's about (disk-)space management, if you add a line of text in front of any other text, the existing text needs to be moved, and this is a rather complicated operation.
If you deal with short files, you could solve that by reading the content of the file into memory and then recreate the file by first writing the new line(s) and the add the content - as Joerg Wood suggested in the comments. However, this would need lot of memory and/or disk IO if the file gets larger, and the process has to be repeated every time you want to add a line - maybe not an issue if you write only one line per hour, but quite an issue if you are writing multiple lines per second.
It seems you are writing a log file and probably you want to see what was going on lately. You could use a windows version of the tail command (that comes from Unix) or use the powershell command Get-Content "C:\Users\[user_name]\Desktop\log.txt" -Tail 10 (see https://stackoverflow.com/a/188126/7599798) for that - it will display the last lines of a file.
An alternative could be to write the log into an Excel sheet or a database - in both cases it is easy to fetch the data in any order.
When I "import" rtf data into word the format are not kept in the same way as when I open the rtf file.
I have a lot of rtf files and want them combined into word. When I use the code I have for csv files the format or the rtf file is missing.
'Define Source
On Error GoTo ErrorHandlerSourcePathIsEmpty
Set SourceContent = Documents.Open(SourceFolder & "\" & TestFile.RTF, Visible:=False)
On Error GoTo 0
'Insert source data into target.
'
On Error GoTo ErrorHandlerTargetBookmark1
wrdDoc.Bookmarks(TargetBookmark1).Range = SourceContent.Range.Text
Application.ScreenUpdating = True
On Error GoTo 0
Am I missing something like "format := SourceFormat" ???
The Text property never carries formatting information, only a string (characters).
There are two possible ways to insert formatted comment from another file into an opened document. Since it appears nothing should be done with the "source content" document there would be no need to open it. In that case, the first possibility (InsertFile method) would usually be preferred: needs fewer resources, faster in execution.
Use the InsertFile method:
Dim sourceContent as String
sourceContent = SourceFolder & "\" & TestFile.RTF
wrdDoc.Bookmarks(TargetBookmark1).Range.InsertFile sourceContent
Use the FormattedText property:
Unlike the Text property, FormattedText carries across formatting. The property needs to be set for both the target and source ranges.
Dim SourceContent as Word.Document
Set SourceContent = Documents.Open(SourceFolder & "\" & TestFile.RTF, Visible:=False)
wrdDoc.Bookmarks(TargetBookmark1).Range.FormattedText = SourceContent.Content.FormattedText
Im creating a vba Function which creates a flat file with just one line, on same directory of my Excel file, everything works fine
but when I print that line which is contained inside of a string I get my message inside of quotation marks
if I expect something like
HDR201412101136452014121090105500000000000000000000
I get this
"HDR201412101136452014121090105500000000000000000000"
this is my code:
Public Function generateFlatFile()
Open ThisWorkbook.Path & "\" & FLAT_FILE_NAME For Output As #1
Dim header As String
header = "HDR"
header = header & Format(Now, "yyyymmddhhnnss")
header = header & Format(Now, "yyyymmdd")
header = header & Worksheets(BD).Cells(2, 3)
header = header & 5
header = header & "00000000000000000000"
Write #1, header
Close #1
End Function
Write #n will enclose strings in quotation marks. If you want full control over how the file gets written, you need to use Print #n instead.
I'm trying to pass a variable from a VBS to BAT but i'm getting "The system cannot find the file specified"
Here is my vbs :
Option Explicit
Dim strFile
strFile = SelectFile( )
If strFile = "" Then
WScript.Echo "No file selected."
Else
WScript.Echo """" & strFile & """"
End If
Function SelectFile( )
Dim objExec, strMSHTA, wshShell
SelectFile = ""
strMSHTA = "mshta.exe ""about:" & "<" & "input type=file id=FILE>" _
& "<" & "script>FILE.click();new ActiveXObject('Scripting.FileSystemObject')" _
& ".GetStandardStream(1).WriteLine(FILE.value);close();resizeTo(0,0);" & "<" & "/script>"""
Set wshShell = CreateObject( "WScript.Shell" )
Set objExec = wshShell.Exec( strMSHTA )
SelectFile = objExec.StdOut.ReadLine( )
Dim wshShelll
Set WshShelll = Wscript.CreateObject("WScript.Shell")
WshShelll.Run "C:\Users\nbendjelida\Desktop\email.bat" & SelectFile
Set objExec = Nothing
Set wshShell = Nothing
Set wshShelll = Nothing
End Function
here is my bat :
"C:\Program Files\Microsoft Office\Office12\Outlook.exe" /eml %1
do you have any idea ?
I repeat the right answer of sachadee with more details to get this question removed from the list of unanswered questions.
Run Method must be called with first parameter being the command to execute with the parameters exactly as when entering the command in the command line window. The examples on the referenced Microsoft help page have also a space character after the command Notepad.
The command line required to call the batch file with a file name as first parameter is:
C:\Users\nbendjelida\Desktop\email.bat name_of_selected_file
But the Windows script host code line
WshShelll.Run "C:\Users\nbendjelida\Desktop\email.bat" & SelectFile
builds the string for the command to run as
C:\Users\nbendjelida\Desktop\email.bat name_of_selected_file
because of the missing space character.
The problem is solved with the correct Windows script host code line
WshShelll.Run "C:\Users\nbendjelida\Desktop\email.bat " & SelectFile
because of the space charater between name of batch file and name of selected file.
If name of selected file contains 1 or more spaces, it is necessary that either variable SelectFile contains already a double quote at beginning and at end, or the necessary double quotes are added on concatenating the command string.
Example with entire batch file name also containing a space character:
Dim FileName
FileName = "%TEMP%\Any File.txt"
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """%USERPROFILE%\Desktop\My Batch File.bat"" """ & FileName & """"
The batch file My Batch File.bat on desktop of current user containing
#echo %0 %*
#pause
outputs for example on Windows 7
"C:\Users\username\Desktop\My Batch File.bat" "C:\User\username\AppData\Local\Temp\Any File.txt"
or on English Windows XP
"C:\Documents and Settings\user name\Desktop\My Batch File.bat" "C:\Documents and Settings\user name\Local Settings\Temp\Any File.txt"
which are the expected results for the command string.
(Yes, a user name can contain a space character although Microsoft recommends not to use a space character in user name, see Microsoft page Creating User and Group Accounts.)
Hello Scripting Experts,
I have a log file on remote servers..
in remote servers c:\vb\text.log
I have included my remote systems in list.Txt like
server1
server2
below is the sample of log..
application working
[10/23/2012 working
[10/24/2012 nos appdown
error found you need to check this
Below is my Script.
Set Fso = CreateObject("Scripting.FileSystemObject")
Set InFile = fso.OpenTextFile("list.Txt")
Set out = fso.CreateTextFile("error.log")
Const ForReading = 1
Do While Not (InFile.atEndOfStream)
strComputer = InFile.ReadLine
today = Date()
Set fso = CreateObject("Scripting.FileSystemObject")
strFilePath = "\\" & strComputer & "\c$\vb\"
Set InputFile = fso.OpenTextFile(strFilePath & "text.log", 1)
Do While Not (InputFile.AtEndOfStream)
strLine = InputFile.ReadLine
If Left(line, Len(today)+1) = "[" & today Then
' line timestamped with today's date
If InStr(line, "nos") > 0 Then
' line contains "error"
out.WriteLine InStr & vbTab & strComputer
End If
End If
Loop
InputFile.close
Loop
out.Close
InFile.Close
Basically the above script should search from current date line only from the text.log file that is [10/24/2012 nos appdown. Then if found as "Nos" in the current date line.. then it should write to the error.log with computer Name.
In my case the output is not coming , however looks like it is searching for the string "Nos".
Kindly gail break me from this situation....
The bug is that you don't specify the explicit option. Like so,
option explicit
This will force VBScript to complain about nondeclared variables. By doing this, you easily can spot misspelled variable names. Delcare variables with dim statement, like so
dim Fso, out
Run the script again and see that you are using a non-existing and non-initialized variable in comparision:
strLine = InputFile.ReadLine ' Read stuff to strLine
If Left(line, Len(today)+1) = "[" & today Then ' ERROR. line has no value!
There are several issues with your adaptation of my script:
As was already pointed out by vonPryz this is the cause of the problem:
strLine = InputFile.ReadLine
If Left(line, Len(today)+1) = "[" & today Then
When you change a variable name from file to strFile you have to change every occurrence of that variable, not just the line where it's assigned.
out.WriteLine InStr & vbTab & strComputer
This line will also fail, because InStr is a function and you don't call it with the correct number of arguments.
today = Date()
This should not be inside a loop unless you expect the date to change during the script run and need to have the current date in every loop cycle.
Set fso = CreateObject("Scripting.FileSystemObject")
fso is instantiated at the beginning of the script. There's no need to re-instantiate it, especially not in each loop cycle. That's just a waste of resources.
Const ForReading = 1
There's no point in defining a constant when you're never using it.
Do While Not ...
Using Do Until ... would be easier to read and to understand.