print a string without quotation marks in a flat file in VBA - vba

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.

Related

Documents.open AND keep the format

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

How would I identify a file to copy based on the date in its name?

I am trying to copy a file from one path to another and rename it. However the source folder contains several files, and the naming convention is the following: 123456_EXyymmdd.txt now the 123456 part is a randomly generated number, so I can only identify the file to copy for a given day by the EXyymmdd part. I have the following code where I tried to put the identifying segment of the string as "**" but it doesn't work, probably due to the date:
Sub SOQuestion()
Dim myDate1 As String
Dim Ipan1 As String
Dim Ipan2 As String
Dim mGlobalDate as string
mGlobalDate=Format(Date, "yyyymmdd")
myDate1 = Format(Date, "yymmdd")
Ipan1 = "157782_EX" & mGlobalDate & ".txt"
Ipan2 = "*_EX*" & myDate1 & ".TXT*"
'source path below
FileCopy "C:\sample\" & Ipan2, "C:\sample2\" & Ipan1
End Sub
It's confused because of the wildcard. It would be like copying a bunch of files to one file, which if you think about it, doesn't make much sense. Instead, use the wildcard and the Dir function to get the exact filename and use that as your source argument.
Dim sFilename as String
sFilename = Dir("C:\sample\" & Ipan2)
Then:
FileCopy "C:\sample\" & sFilename, "C:\sample2\" & Ipan1
MSDN Dir Function

closing an active excel file knowing fraction of the name

I have opened a file given the fraction of the name, where i equals to 142 as per below code.
Workbooks.Open Filename:=FilePath3 & "" & i & "."
After switching back and forth between other files is it possible to return back to this file and close it? I cant figure out how to Reference/Activate it, given I only have fraction of the name.
Thanks
I guess, after you open this file it's automatically activated, so I'd make it like:
Dim fileName as String
Workbooks.Open Filename:=FilePath3 & "" & i & "."
fileName = ActiveWorkbook.Name
and from this moment you can close your file at any time with something like:
Workbooks(fileName ).Close (False)
use (False) only if you don't want to save it

Stop Access writing two sets of double quotes to csv

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

Using VBA, how do I save a file in a relative directory

I have the following code to save the contents of an Excel Workbook as a tab delimited file.
Sub maketxtfile(className As String, rosterFileHandle As String)
Dim i As Long, gradebookContent As String
With Worksheets(className).UsedRange
For i = 1 To .Rows.Count
gradebookContent = gradebookContent & vbCrLf & Join$(Application.Transpose(Application.Transpose(.Rows(i).Value)), vbTab)
Next
End With
Open Replace(ThisWorkbook.FullName, "Fall_2013_2014.xlsm", rosterFileHandle) For Output As #1
Print #1, Mid$(gradebookContent, Len(vbCrLf) + 1)
Close #1
End Sub
The problem is that I don't want the tab delimited file to reside in the same directory as the xlsm file. I would like the file to reside in a subdirectory. I've seen solutions posted using absolute path names. That's not an option for me, I don't necessarily know what the path name will be in advance.
I thought I could do something like:
Open Replace(ThisWorkbook.FullName, "Fall_2013_2014.xlsm", "rosters/" & rosterFileHandle) For Output As #1
Print #1, Mid$(gradebookContent, Len(vbCrLf) + 1)
Close #1
But this got me an error. Though I'm working on a Mac, I tried using "rosters\" but while this worked, it did not place my file in the subdirectory, but in a file with \\ in its path name.
I would greatly appreciate a solution that will show me how to do this using relative path names.
Incidentally, I would not mind first creating the tab delimited file in the current directory and then moving it into a subdirectory.
Mac uses : as the path separator; it only looks weird if you're used to DOS/Windows. Or perhaps if you're a dyslexic *nix user ;-).
If by "my other machines" you mean Windows boxes, then no, it won't be portable, since the colon is restricted to delimiting drive letters in file names. Best bet is to do something like this:
Function PathSep() As String
#If Mac Then
PathSep = ":"
#Else
PathSep = "\"
#End If
End Function
Then you could:
Open Replace(ThisWorkbook.FullName, "Fall_2013_2014.xlsm", "." & PathSep & "rosters" & PathSep & rosterFileHandle) For Output As #1
After much searching, I found something that works.
I can write:
Open Replace(ThisWorkbook.FullName, "Fall_2013_2014.xlsm", ".:rosters:" & rosterFileHandle) For Output As #1
Print #1, Mid$(gradebookContent, Len(vbCrLf) + 1)
Close #1
The syntax seems a bit weird using ":" to indicate the directory path, but it works. Now the question is whether this is portable and will work correctly on my other machines.
This should do the trick
ThisWorkbook.SaveAs (ThisWorkbook.Path & "\Rosters\" & ThisWorkbook.Name)
Edit:
Changed code to save the text file in stead also used chr(92) to reporesent the path seperator.
Sub maketxtfile()
Dim i As Long, gradebookContent As String
Dim rosterFileHandle As String
rosterFileHandle = "tabtest.txt"
rosterFileHandle = ThisWorkbook.Path & Chr(92) & "Rosters" & Chr(92) & rosterFileHandle
With ActiveSheet.UsedRange
For i = 1 To 10
gradebookContent = gradebookContent & vbCrLf & Join$(Application.Transpose(Application.Transpose(.Rows(i).Value)), vbTab)
Next
End With
Open (rosterFileHandle) For Output As #1
Print #1, Mid$(gradebookContent, Len(vbCrLf) + 1)
Close #1
End Sub