Input Text File into Excel Form - vba

I have a text file that contains anywhere from 30 lines to 1000 lines of data in there with each line containing anywhere from 10 to 200 characters. I'm trying to input this data into a text box on a user form when it initializes.
Code that I'm using now...
Private Sub UserForm_Initialize()
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
FilePath = "C:\PATH\MyText.txt"
TextFile = FreeFile
Open FilePath For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)
'MsgBox FileContent
UserForm1.TextBox1 = Input(LOF(TextFile), TextFile)
Close TextFile
End Sub
It works fine when I try outputting the data to a MsgBox (however doesn't show ALL data), but when I try to output it to the TextBox I get the error...
Run-time error '62':
Input past end of file
I'm guessing it's not ready the EOF flag here... How would I go about doing this? Maybe it's because the input file is too large?
Any ideas or suggestions would be great!

Input moves the "pointer" as it reads the file.
You read the entire file here:
FileContent = Input(LOF(TextFile), TextFile)
Then once again here:
UserForm1.TextBox1 = Input(LOF(TextFile), TextFile)
But by then FileContent already has your entire content, and file handle#TextFile is already at EOF. So when you try to input again, you're inputting past the end of the file.
Just close the file immediately after reading it, and then do UserForm1.TextBox1 = FileContent.
No need to [try to] read the file twice: you did read the whole contents into FileContent. The reason why a MsgBox truncates it is because, well, a MsgBox (just like a cell) isn't made for this, and has a maximum content length. TextBox1 should be able to handle it (unless you gave it a MaxLength value).

Related

excel vba button to add text to a file

I am creating a spreadsheet with a button which creates a new file, then adds text to the file. I can't seem to get it working properly. (It is actually json, but for my purposes it is just raw text being inserted into a file.)
This is the code i have so far. It creates a new file and puts some text in it, I can't get the formatting of the text to come out how I want it. I don't really understand why the quotes appear in the output.
Private Sub GENERATE_ORDER_BUTTON_Click()
Dim path As String
path = "H:\order.json"
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.createtextfile(path, True)
a.WriteLine ("{")
a.Close
Dim outputstring As String
outputstring = "test" & "anothertest"
Open path For Append As #1
Write #1, outputstring
Close #1
End Sub
What i am finding is the output comes out like this:
{
"testanothertest"
The ultimate goal is to create a file with the indentations, quotes etc exactly as it is below.
{
"BASE_CE": [
{
"CE_HOSTNAME": "TESTCE-DCNCE-01",
"NEW": "NEW",
How to create and write to a txt file using VBA
I think this could maybe help you.
Cause if you use print,it doesn't appear to be formated like you dont want it to be...
Private Sub GENERATE_ORDER_BUTTON_Click()
Dim path As String
path = "J:\order.json"
Set fs = CreateObject("Scripting.FileSystemObject")
Set a = fs.createtextfile(path, True)
a.WriteLine ("{")
a.Close
Dim outputstring As String
outputstring = "test" & "anothertest"
Open path For Append As #1
Print #1, outputstring
Close #1
End Sub

Addition of Dialog Boxes for File Open and File Save As after Text Replacement

I have a script that replaces delimiters in a file provided by an outside source. The script works fine as is, but I'd like to add the ability to Select a file using a dialog, and save a file as something else using the save as dialog after the replacements are made.
I've tried a few different ways found here and in the MSDN documentation and the boxes open, however no data is replaced and no file is saved. Maybe I'm not wording my search correctly. I haven't used dialog boxes in the past :(
Sub RosterDelimiters_FindReplace()
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
FilePath = "C:\ReplaceText\Roster.txt"
TextFile = FreeFile
Open FilePath For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)
Close TextFile
FileContent = Replace(FileContent, ";+;", ",")
FileContent = Replace(FileContent, ";", ",")
TextFile = FreeFile
Open FilePath For Output As TextFile
Print #TextFile, FileContent
Close TextFile
End Sub
Resulting actions preferred in pseudocode:
Sub
Dialog Box Opens
TextFile is selected
Replacements Run
Save As Box Opens
File is Named and Saved Wherever
End Sub

How to Access a txt file in a Folder created inside a VB project

I'm creating a VB project for Quiz App (in VS 2013). So I have some preset questions which are inside the project (I have created a folder inside my project and added a text file).
My question is how can I read and write contents to that file? Or if not is there any way to copy that txt file to Documents/MyAppname when installing the app so that I can edit it from that location?
In the example below I am focusing on accessing files one folder under the executable folder, not in another folder else wheres. Files are read if they exists and then depending on the first character on each line upper or lower case the line then save data back to the same file. Of course there are many ways to work with files, this is but one.
The following, created in the project folder in Solution Explorer a folder named Files, add to text files, textfile1.txt and textfile2.txt. Place several non empty lines in each with each line starting with a character. Each textfile, set in properties under solution explorer Copy to Output Directory to "Copy if newer".
Hopefully this is in tune with what you want. It may or may not work as expected via ClickOnce as I don't use ClickOnce to validate this.
In a form, one button with the following code.
Public Class Form1
Private TextFilePath As String =
IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Files")
Private TextFiles As New List(Of String) From
{
"TextFile1.txt",
"TextFile2.txt",
"TextFile3.txt"
}
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim FileName As String = ""
' loop thru each file
For Each fileBaseName As String In TextFiles
FileName = IO.Path.Combine(TextFilePath, fileBaseName)
' only access file if it exist currently
If IO.File.Exists(FileName) Then
' read file into string array
Dim contents As String() = IO.File.ReadAllLines(FileName)
' upper or lower case line based on first char.
' this means you can flip flop on each click on the button
For x As Integer = 0 To contents.Count - 1
If Char.IsUpper(CChar(contents(x))) Then
contents(x) = contents(x).ToLower
Else
contents(x) = contents(x).ToUpper
End If
Next
' save changes, being pesstimistic so we use a try-catch
Try
IO.File.WriteAllLines(FileName, contents)
Catch ex As Exception
Console.WriteLine("Attempted to save {0} failed. Error: {1}",
FileName,
ex.Message)
End Try
Else
Console.WriteLine("Does not exists {0}", FileName)
End If
Next
End Sub
End Class
This may help you
Dim objStreamReader As StreamReader
Dim strLine As String
'Pass the file path and the file name to the StreamReader constructor.
objStreamReader = New StreamReader("C:\Boot.ini")
'Read the first line of text.
strLine = objStreamReader.ReadLine
'Continue to read until you reach the end of the file.
Do While Not strLine Is Nothing
'Write the line to the Console window.
Console.WriteLine(strLine)
'Read the next line.
strLine = objStreamReader.ReadLine
Loop
'Close the file.
objStreamReader.Close()
Console.ReadLine()
You can also check this link.

Reading a .dat file

I have a file I am trying to read and disply results into a text box. The file has no extension, but it is a 'data' file per the website (www.checkfiletype.com).
Here is a screen shot of how the file looks in a online reader, it looks like hex?
I have tried a stream reader, and gives nothing in results. Last method I tried was a BinaryReader, that I have never used before. The results from this is a "0" into the text box. Given that I have never used the BinaryReader function, I am sure I did something wrong with it.
Using reader As New BinaryReader(File.Open("C:\Users\jefhill\Desktop\CMOSDATA", FileMode.Open))
Dim pos As Integer = 0
Dim length As Integer = reader.BaseStream.Length
While pos < length
' Read the integer.
Dim value As Integer = reader.ReadInt32()
' Write to screen.
TextBox1.Text = value
' Add length of integer in bytes to position.
pos += 4
End While
End Using
Any help would be greatly appreciated.
EDIT
I tried using a basic StreamReader. With this, nothing happens, as in no errors, just puts nothing(blank) into the textbox.
Dim file As String = "C:\Users\jefhill\Desktop\CMOSDATA"
Dim reader As New System.IO.StreamReader(file)
TextBox1.Text = reader.ReadToEnd
reader.Close()
The file is not a text file, and cannot be directly displayed in a TextBox. You will need to find the format of the file and convert it to text in order to display it in a TextBox.

I am trying to use VBA code to save inkpicture contents, can only use vb.net or C#

I found this code that is missing the function call in the last line, any ideas on what the save to file command would be?, I'll just kludge it in.
'CODE to SAVE InkPicture to FILE
Dim objInk As MSINKAUTLib.InkPicture
Dim bytArr() As Byte
Dim File1 As String
File1 = "C:\" & TrainerSig & ".gif"
Set objInk = Me.InkPicture2.Object
If objInk.Ink.Strokes.Count > 0 Then
bytArr = objInk.Ink.Save(2)
fSaveFile bytArr, File1
End If
Here is a kludgy version of saving .InkPicture with VBA code in Access 2007 to a .isf file.
Private Sub Command283_Click()
'CODE to SAVE InkPicture to FILE
Dim objInk As MSINKAUTLib.InkPicture
Dim bytArr() As Byte
Dim File1 As String
File1 = "C:\test.isf"
Set objInk = Me.InkPicture2.Object
If objInk.Ink.Strokes.Count > 0 Then
bytArr = objInk.Ink.Save(2)
Open File1 For Binary As #1
Put #1, , bytArr
Close #1
End If
End Sub
I tried zaphod23's solution and it did not work for me. I also thought it quite strange that the solution would save in a .isf format, normally people want to save inkPicture contents to an image file (jpg, gif, etc.). It took me a while to hunt down the pieces of this code and put it together, so I'll post it here for others who might find it useful.
This takes an inkPicture object used for a signature panel in a Microsoft Access form, saves the contents as a gif image, then puts the image in an image object on the form (which is useful because the inkPicture contents will not show up when you go to print the form).
On Error Resume Next
Dim imgBytes() As Byte
Dim sFilePathAndName As String
imgBytes = Me.signaturePanel.Ink.Save(IPF_GIF)
If (UBound(imgBytes) = 0) Then
MsgBox ("Please enter your signature")
Else
sFilePathAndName = (Application.CurrentProject.Path & "\images\system\signatures\" & "signature")
Open sFilePathAndName For Binary Access Write As #1
Put #1, 1, imgBytes
Close #1
Me.imgSignature.Picture = sFilePathAndName
End If