excel vba button to add text to a file - vba

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

Related

Moving Files From One Folder To Another VB.Net

I am trying to figure out how to move 5 files
settings.txt
settings2.txt
settings3.txt
settings4.txt
settings5.txt
from one folder to another.
Although I know what the file names will be and what folder Name they will be in, I don't know where that folder will be on the Users computer.
My thought process is to use a FolderBrowseDialog which the user can browse to where the Folder is, and then when OK is pressed, it will perform the File copy to the destination folder, overwriting what's there.
This is what I have so far.
Dim FolderPath As String
Dim result As Windows.Forms.DialogResult = FolderBrowserImport.ShowDialog()
If result = DialogResult.OK Then
FolderPath = FolderBrowserImport.SelectedPath & "\"
My.Computer.FileSystem.CopyFile(
FolderPath & "settings.txt", "c:\test\settings.txt", overwrite:=True)
ElseIf result = DialogResult.Cancel Then
Exit Sub
End If
Rather than run this 5 times, is there a way where it can copy all 5 files at once
I know why IdleMind recommended the approach they did, but it would probably make for a bit more readable code to just list out the file names:
Imports System.IO
...
Dim result = FolderBrowserImport.ShowDialog()
If result <> DialogResult.OK Then Exit Sub
For Each s as String in {"settings.txt", "settings2.txt", "settings3.txt", "settings4.txt", "settings5.txt" }
File.Copy( _
Path.Combine(FolderBrowserImport.SelectedPath, s), _
Path.Combine("c:\test", s), _
True _
)
Next s
You can swap this fixed array out for a list that VB prepares for you:
For Each s as String in Directory.GetFiles(FolderBrowserImport.SelectedPath, "settings*.txt", SearchOption.TopDirectoryOnly)
File.Copy(s, Path.Combine("c:\test", Path.GetFilename(s)), True)
Next s
Tips:
It's usually cleaner to do a If bad Then Exit Sub than a If good Then (big load of indented code) End If - test all your known failure conditions at the start and exit the sub if anything fails, rather than arranging a huge amount of indented code
Use Path.Combine to combine path and filenames etc; it knows how to deal with stray \ characters
Use Imports to import namespaces rather than spelling everything out all the time (System.Windows.Forms.DialogResult - a winforms app will probably have all the necessaries imported already in the partial class so you can just say DialogResult. If you get a red wiggly line, point to the adjacent lightbulb and choose to import System.WIndows/Forms etc)
Once you have the selected folder, use a For loop to build up the names of the files you're looking for. Use System.IO.File.Exists() to see if they are there. Use System.IO.Path.Combine() to properly combine your folders with the filenames.
Here's a full example (without exception handling, which should be added):
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If FolderBrowserImport.ShowDialog() = DialogResult.OK Then
Dim FolderPath As String = FolderBrowserImport.SelectedPath
For i As Integer = 1 To 5
Dim FileName As String = "settings" & If(i = 1, "", i) & ".txt"
Dim FullPathFileName As String = System.IO.Path.Combine(FolderPath, FileName)
If System.IO.File.Exists(FullPathFileName) Then
Dim DestinationFullPathFileName = System.IO.Path.Combine("c:\test", FileName)
My.Computer.FileSystem.CopyFile(FullPathFileName, DestinationFullPathFileName, True)
Else
' possibly do something in here if the file does not exist?
MessageBox.Show("File not found: " & FullPathFileName)
End If
Next
End If
End Sub

Writing/Reading from text files in VB.net

I am a student in computer science and for a project I need to be able to read from a text file in a way that each line is assigned to a space within an array. This should happen so that each line of text file is read in the order that it appears in the text file. I would also appreciate any methods of writing to a text file as well.
If this question is already explained, could you please direct me to the existing answer.
Things to note:
1) I am coding in a console application in VB.NET
2) I am relatively new at coding
You can do it like this:
Dim sFile As String = "D:\File.txt"
Dim aLines As String() = System.IO.File.ReadAllLines(sFile)
System.IO.File.WriteAllLines(sFile, aLines)
Here's a sample from the official documentation:
Imports System.IO
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Dim sw As StreamWriter
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
Dim createText() As String = {"Hello", "And", "Welcome"}
File.WriteAllLines(path, createText)
End If
' This text is always added, making the file longer over time
' if it is not deleted.
Dim appendText As String = "This is extra text" + Environment.NewLine
File.AppendAllText(path, appendText)
' Open the file to read from.
Dim readText() As String = File.ReadAllLines(path)
Dim s As String
For Each s In readText
Console.WriteLine(s)
Next
End Sub
End Class
Remarks
This method opens a file, reads each line of the file, then adds each line as an element of a string array. It then closes the file. A line is defined as a sequence of characters followed by a carriage return ('\r'), a line feed ('\n'), or a carriage return immediately followed by a line feed. The resulting string does not contain the terminating carriage return and/or line feed.
Module Module1
Sub Main()
'Declare four variables
Dim oReader As New System.IO.StreamReader(".\archive01.txt") 'This file has to exist in the aplication current directory.
Dim oWriter As New System.IO.StreamWriter(".\archive02.txt") 'This file will be created by the software.
Dim oArray() As String = {}
Dim oString As String = Nothing
'For reading from .\archive01.txt and to load in oArray().
oString = oReader.ReadLine
While Not oString Is Nothing
If UBound(oArray) = -1 Then 'Ubound = Upper Bound, also exist LBound = Lower Bound.
ReDim oArray(UBound(oArray) + 1)
Else
ReDim Preserve oArray(UBound(oArray) + 1)
End If
oArray(UBound(oArray)) = New String(oString)
oString = oReader.ReadLine
End While
oReader.Close()
'For writing from oArray() to .\archive02.txt.
For i = 0 To oArray.Count - 1 Step 1
oWriter.WriteLine(oArray(i))
Next
oWriter.Close()
End Sub
End Module
Hi, try with this code. It works well. I hope that this helps to you to learn how to do this kind of things. Thank you very much. And happy codding!. :)

Trying to write files on multiple lines

i am trying to have variables linked to together like this: (login,pass,name) i want to have several line of those but whenever i register it clears the file help would be appreciated thanks.
Private Sub btn_register_Click(sender As Object, e As EventArgs) Handles btn_register.Click
Dim newline As String
Dim anything As String
password = txt_passwordregister.Text
username = txt_usernameregister.Text
If password <> "" And username <> "" Then
If validatepass() = False Then
MsgBox("please enter more than 8 characters")
Else
newline = txt_usernameregister.Text & "," & txt_passwordregister.Text
If rad_student.Checked Then
anything = newline & "," & txt_fullname.Text
Student.WriteLine(anything)
Student.Close()
Else
End If
MsgBox("You are now registered!")
End If
End If
End Sub
You might want to specify what kind of file you are talking to.
but since you don't actually indicate something in particular, here i used StreamWriter to append lines of text to a file.
Using studentWriter As StreamWriter = New StreamWriter("(<path>\<filename>.<txt>)", True)
studentWriter.WriteLine(anything)
End Using
sorry for my bad english.
You didnt show what's happening with the object Student before..
We assume you are using StreamWriter here??
Our best guess is that you open the file in new file mode rather than append mode..
To enable Append mode, provide the parameter when you create the Student object like this :
Dim Student as New StreamWriter("[File Location]",[Append Mode])
When [Append Mode] is True it will append the file and write after the last line you've written into it before.
When [Append Mode] is False it will treat the file as a new file and all the content inside will be lost.

How do you store strings in a .txt file?

I've been creating a program over the past few days. The program stores a string "Dim info As String = Nothing" where the input is asked later.
EG: I input "Hello World!" to the variable 'info', how do I store the value of 'info' (Hello World!) to a .txt file? Or is this not possible?
(Still a beginner to vb.net, looking for simple answers.)
Attempt 1 (Find error please):
Sub Main()
Dim path As String = "C:\VBTextFiles\Test1.txt"
Dim stringex As String = "Hello world!"
File.WriteAllText(path, stringex)
End Sub
You could use IO.File.WriteAllText to create a file and write your info into it.
This page has examples for Create and Append. Here is a revelant part for Create:
Dim path As String = "c:\temp\MyTest.txt"
' This text is added only once to the file.
If File.Exists(path) = False Then
' Create a file to write to.
Dim createText As String = "Hello and Welcome" + Environment.NewLine
File.WriteAllText(path, createText)
End If
For APPEND, use AppendAllText. See Example.
Dim path As String = "c:\temp\MyTest.txt"
' This text is added only once to the file.
If File.Exists(path) = True Then
' Create a file to write to.
Dim createText As String = "Hello and Welcome" + Environment.NewLine
File.WriteAllText(path, createText)
End If
Change False for True in the line 3 :)

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