Converting Dos Text Files to Unix in VBA fails - vba

I've followed the suggestion in a prior question and grabbed this code but I don't get a useable file out of it. I've looked at it and don't see the problem.
Public Enum ConvertType
dos2unix = 0
unix2dos = 1
End Enum
Public Function ConvertFile(OriginalFile As String, NewFile As String, eConvertType As ConvertType, _
Optional DeleteOriginal As Boolean = False)
Dim OpenFileNum, SaveFileNum As Integer
Dim NewFileBuffer As String
' This function will open a file and convert it to
' a txt file format usable under *nix or dos
On Error GoTo Error_Found
OpenFileNum = FreeFile ' grab the first free file
Open OriginalFile For Input As #OpenFileNum ' open the unix file
SaveFileNum = FreeFile ' get another free file to write to
Open NewFile For Binary As #SaveFileNum ' open/create the save file
Do While Not EOF(OpenFileNum)
Line Input #OpenFileNum, NewFileBuffer ' retrive the text (if a unix file, then the entire text is on one line)
If eConvertType = dos2unix Then ' Check what type of conversion to do
NewFileBuffer = NewFileBuffer & Chr(10)
Else
NewFileBuffer = Replace(NewFileBuffer, Chr(10), vbCrLf)
End If
Put #SaveFileNum, , NewFileBuffer ' write out the file
Loop
Close #SaveFileNum
Close #OpenFileNum
If DeleteOriginal = True Then Kill OriginalFile
Exit_Sub:
Exit Function

Try this:
Option Explicit
Sub testConversion()
convertFile "C:\test.txt"
End Sub
Public Sub convertFile(ByVal fileName As String)
Const Dos2Unix = 1
Dim fs As Object, txt As String
Set fs = CreateObject("Scripting.FileSystemObject")
txt = fs.OpenTextFile(fileName, 1).ReadAll 'ForReading = 1
txt = IIf(Dos2Unix = 1, Replace(txt, vbCrLf, vbLf), Replace(txt, vbLf, vbCrLf))
fs.OpenTextFile(fileName, 2).Write txt 'ForWriting = 2
End Sub
Notes:
In Notepad (Windows) all lines will appear on one continuous line
All CarriageReturn–Linefeed combinations are replaced by Linefeed characters

Related

VBA - Reading a text file, splitting it into array and printing it back in VBA Word

Hello I would like to take my txt file containing string of data, split it into array by line. However, I am not able to either input data to array correctly or I have problem with the function GetArrLength. I am pretty new to VBA and can't figure the problem out. The macro stops with Run-time error '13': type mismatch and highlights this section of the code:
GetArrLength = UBound(arr) - LBound(arr) + 1
Hopefully it's not a big issue.
Thanks for any ideas.
Sub apokus()
'PURPOSE: Send All Data From Text File To A String Variable
Dim TextFile As Integer
Dim filePath As String
Dim FileContent As String
Dim strAll As String
Dim arrString() As String
'File Path of Text File
filePath = InputBox("Path to your MD file.", "Path to MD", "actual path to the file")
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file
Open filePath For Input As TextFile
'Store file content inside a variable
FileContent = Input(LOF(TextFile), TextFile)
Close TextFile
arrString = Strings.Split(FileContent, vbCr)
Selection.TypeText Text:=GetArrLength(1)
Dim i As Long
For i = 1 To GetArrLength(arrString)
Selection.TypeText Text:=GetArrLength(i) + vbNewLine
Next i
End Sub
Public Function GetArrLength(arr As Variant) As Long
If IsEmpty(arr) Then
GetArrLength = 0
Else
GetArrLength = UBound(arr) - LBound(arr) + 1
End If
End Function
Your code should be as follows:
arrString = Strings.Split(FileContent, vbCr)
Selection.TypeText Text:=GetArrLength(arrString)
Dim i As Long
For i = 0 To UBound(arrString)
Selection.TypeText Text:=arrString(i) + vbNewLine
Next i
However, I can't see the point of your code. You take a text file that contains a number of paragraphs, remove the carriage returns, then insert the text into Word adding carriage returns back in.

How to remove the empty line that excel makes when creating a csv file using vba

As some of you probably know, excel creates an empty line at the end of CSV files. I'm looking for a solution that can remove/delete this line because I want to upload the CSV file to a different program, which can't handle this empty line.
First I thought it was the way I created the CSV file, but after spending hours searching for a solution, I found out that it's a bug.
Does anybody have a solution to this problem, removing the last line in a CSV file using VBA?
Try calling this Sub to kill the last line of the csv-file. You have to insert the path into the code:
Sub KillLastLine()
Dim fso As New FileSystemObject
Dim ts As TextStream
Dim filecontent As String
Dim myFile As File
Set myFile = fso.GetFile("YourCSVPathHere")
Set ts = myFile.OpenAsTextStream(ForReading)
While Not ts.AtEndOfStream
filecontent = filecontent & ts.ReadLine & vbCrLf
Wend
Set ts = myFile.OpenAsTextStream(ForWriting)
ts.Write Left(filecontent, Len(filecontent) - 1)
ts.Close
End Sub
Sub ZUtil_TextFile_FindReplace(FilePath As String, strOld As String, strNew As String)
'PURPOSE: Modify Contents of a text file using Find/Replace
'SOURCE: www.TheSpreadsheetGuru.com
Dim TextFile As Integer
Dim FileContent As String
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Read State
Open FilePath For Input As TextFile
'Store file content inside a variable
FileContent = Input(LOF(TextFile), TextFile)
'Clost Text File
Close TextFile
'Find/Replace
FileContent = Replace(FileContent, strOld, strNew)
FileContent = Replace(FileContent, "^(?:[\t ]*(?:\r?\n|\r))+", "")
If Right(FileContent, 2) = Chr(13) & Chr(10) Then
FileContent = Left(FileContent, Len(FileContent) - 2)
End If
'Determine the next file number available for use by the FileOpen function
TextFile = FreeFile
'Open the text file in a Write State
Open FilePath For Output As TextFile
'Write New Text data to file
Print #TextFile, FileContent
'Close Text File
Close TextFile
'MsgBox "ZUtil_TextFile_FindReplace TERMINADO"
End Sub

Open text file, get number/text from file and increment text/number by 1

I have a .txt file, Supplier Count.txt and in my excel spreadsheet, each time I run a VBA code I want this file to be opened, to read the number value in my text file, e.g. '21' and then increment it by 1.
So say our text file has one line of text, and this line of text is a number, '21'. the vba code should open the file, read this number and increment it by 1 and replace the text, save it and close the text file. so our value is then '22'
does anyone know how I can do this as I am completely new to vba and so far all ive been able to come up with is the opening the text file and reading the number out as a msgbox
Application.ScreenUpdating = False
On Error GoTo ErrHandler12:
Dim FilePath12 As String
Dim Total12 As String
Dim strLine12 As String
FilePath12 = "\\ServerFilePath\assets\Supplier Count.txt"
Open FilePath12 For Input As #1
While EOF(1) = False
'read the next line of data in the text file
Line Input #1, strLine12
Total12 = Total12 & vbNewLine & strLine12
'increment the row counter
i = i + 1
Wend
Close #1
MsgBox Total12
ErrHandler12:
Application.ScreenUpdating = True
First include a reference to the FileSystemObject (see https://stackoverflow.com/a/5798392/380384)
Then run this
Private fso As New FileSystemObject
Public Sub IncrCount()
Dim path As String
path = fso.BuildPath("\\server\share\folder", "SupplierCount.txt")
Dim fs As TextStream
Set fs = fso.OpenTextFile(path, ForReading)
Dim counter As Long
counter = CInt(fs.ReadLine())
fs.Close
Set fs = fso.OpenTextFile(path, ForWriting, True)
fs.WriteLine CStr(counter + 1)
fs.Close
End Sub

Search a folder for keyword

I'm looking to search a folder for a keyword term 'fuel', to pull information from returned files into a 'data' sheet.
For instance, I have a folder week numbers (1 - 52 cross the year so in the new year this will contain one folder but will build as the year goes on).
I search this folder for all .doc files contains the word 'fuel'.
You can do this via a Windows search by typing "fuel" in the search function in the top corner and it will display all filenames and all files that contains the word 'fuel'.
I have this for searching for a file that has 'fuel' in its name, but not inside it.
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
file = Dir("c:\testfolder\")
While (file <> "")
If InStr(file, "fuel") > 0 Then
MsgBox "found " & file
Exit Sub
End If
file = Dir
Wend
End Sub
It isn't particularly pretty, but think something like this should work:
Sub loopThroughFiles()
Dim file As String
file = FindFiles("C:\TestFolder", "fuel")
If (file <> "") Then MsgBox file
End Sub
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Sheell Command And Get Output
Dim files As String
Dim lines
files = CreateObject("Wscript.Shell").Exec("FIND """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
lines = Split(files, vbCrLf)
' Look for matching files
Dim curFile As String
Dim line
For Each line In lines
If (Left(line, 11) = "---------- ") Then
curFile = Mid(line, 12)
End If
If (line = target) Then
FindFiles = curFile
Exit Function
End If
Next
FindFiles = ""
End Function
Uses the FIND command line and then reads the output (hence needing to use Wscript.Shell) and returns first match, or empty string if no file is found
Following #BLUEPIXY's command FINDSTR /M the function can be replaced by:
Function FindFiles(ByVal path As String, ByVal target As String) As String
' Run The Shell Command And Get Output
Dim files As String
files = CreateObject("Wscript.Shell").Exec("FINDSTR /M """ & target & """ """ & path & "\*.*""").StdOut.ReadAll
FindFiles = ""
If (files <> "") Then
Dim idx As Integer
idx = InStr(files, vbCrLf)
FindFiles = Left(files, idx - 1)
End If
End Function

How to get the browse file path in text box using VBA?

How to get the browse file name into text box ? if get the file path, how to split the file name?
I tried application.GetOpenFilename("Text Files(*.txt),*.txt")
Please advise to display into the text box and how to split the exact file name only to read the text file?
Don't waste your time reinventing the wheel: the FileSystemObject will do this for you.
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Sheet1.TextBox1.Text = FSO.GetFilename("C:\mydir\myfile.dat")
The textbox now contains the text myfile.dat.
The Dir function will give you the file name as long as it's a file that exists - and yours will be if you use GetOpenFilename.
Sub GetFileName()
Dim sFullName As String
Dim sFileName As String
sFullName = Application.GetOpenFilename("*.txt,*.txt")
sFileName = Dir(sFullName)
Debug.Print sFullName, sFileName
End Sub
Here is a VBA routine to return the file name stripped of its path. Its easily modified to return the path instead, or both.
'====================================================================================
' Returns the file name without a path via file open dialog box
'====================================================================================
' Prompts user to select a file. Which ever file is selected, the function returns
' the filename stripped of the path.
Function GetAFileName() As String
Dim someFileName As Variant
Dim folderName As String
Dim i As Integer
Const STRING_NOT_FOUND As Integer = 0
'select a file using a dialog and get the full name with path included
someFileName = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If someFileName <> False Then
'strip off the folder path
folderName = vbNullString
i = 1
While STRING_NOT_FOUND < i
i = InStr(1, someFileName, "\", vbTextCompare) 'returns position of the first backslash "\"
If i <> STRING_NOT_FOUND Then
folderName = folderName & Left(someFileName, i)
someFileName = Right(someFileName, Len(someFileName) - i)
Else 'no backslash was found... we are done
GetAFileName = someFileName
End If
Wend
Else
GetAFileName = vbNullString
End If
End Function
Easiest way is to simply read from the final "\";
tbx.text = mid$(someFileName, 1 + InStrRev(someFileName, "\"), Len(someFileName))
Button1 click
OpenFileDialog1.ShowDialog()
Me.TextBox1.Text = OpenFileDialog1.FileName
End Sub
Textbox1 change
Dim File As System.IO.FileInfo
File = My.Computer.FileSystem.GetFileInfo(TextBox1.Text)
Dim Path As String = File.DirectoryName
TextBox2.Text = Path
Dim fileName As String = File.Name
TextBox3.Text = fileName
End Sub