How to change section text in INI file using Word VBA - vba

I have to change the section in an ini-file using Word VBA.
I know how to change the values of the keys, but can anyone tell me how to change the value of a section (the first section = the only section)?
In the example below I like to change OldName in NewName.
[Offices]
Office1=OldName
[OldName]
Key1=value
Key2=value
etc.
Thanks,
Kem

You can use this code to replace text in any text file
Public Sub Test()
ReplaceInTXT "C:\folder\file.ini", "[OldName]", "[NewName]"
End Sub
Public Sub ReplaceInTXT(sFileName As String, sFind As String, sReplace As String)
Dim Content As String
Dim hFile As Long
hFile = FreeFile
Open sFileName For Input As #hFile
Content = Input$(LOF(hFile), hFile)
Close #hFile
Content = Replace(Content, sFind, sReplace)
Open sFileName For Output As #1
Print #1, Content
Close #1
End Sub
Please make sure to have a backup first. I don't want to mess up the file

Related

How to read all information from shell command in VBA and save it in .txt file

I try to use this code:
Shell(nppPath & " " & fileToOpen, vbNormalFocus)
which opens txt file nppPath = "C:\Windows\notepad.exe" but I cannot read from it and save it as .txt file using VBA.
Looking forward to any suggestions.
I'm presuming you copied the nppPath over wrong as it should be
nppPath = "C:\Windows\System32\notepad.exe"
but for reading from the text file you could use free file:
Dim IntFile As Integer, StrFileName As String, StrFileContent As String
StrFileName = fileToOpen 'Your file location here
IntFile = FreeFile
Open StrFileName For Input As #IntFile
StrFileContent = Input(LOF(IntFile), IntFile) 'This now contains the text
Close #IntFile
This will read the text file into a single variable that you can then use however you wish.
If you want to write to a text file you can use the following code:
Dim StrNewLocation As String, StrFileContent As String
StrNewLocation = "" 'Put the new files name and location here
StrFileContent = "Example" 'The text to go into the new file
Open StrNewLocation For Output As #1
Write #1, StrFileContent
Close #1
Hopefully this helps you solve your problem if not send me a message and I'll see what I can do.

VBA: Replace text from txt for each line and save as

Could somebody help me with the following? I tried making it on my own, but all I could do is open a txt and replace a static word with static word.
VBA script:
Open and Read first line of ThisVbaPath.WordsToUse.txt
Open and Find USER_INPUT in ThisVbaPath.BaseDoc.docx (or txt)
Replace all occurrence of USER_INPUT with first line from WordsToUse.txt
Save BaseDoc.docx as BaseDoc&First_Line.docx
Close all
Go next line and do same, but don't ask for user input, use previous one
If error go next
When done show if there were any errors (unlikely I guess)
I would use it about weekly for 150-ish lines.
Thanks!
I think something like this should work?
Sub test()
Dim text, textReplace, findMe As String
findMe = InputBox("What Text To Find?")
Open "C:\Excel Scripts\test.txt" For Input As #1
Open "C:\Excel Scripts\test2.txt" For Input As #2
Open "C:\Excel Scripts\output.txt" For Output As #3
While Not EOF(1)
Line Input #1, text
While Not EOF(2)
Line Input #2, textReplace
Write #3, Replace(text, findMe, textReplace)
Wend
Wend
Close #1
Close #2
Close #3
End Sub
Sub TextFile_FindReplace()
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
FilePath = Application.ActiveWorkbook.Path & "\NEWTEST.txt"
TextFile = FreeFile
Open FilePath For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)
FileContent = Replace(FileContent, "FOO", "BAR")
Print #TextFile, FileContent
Close TextFile
End Sub

Excel VBA: Make InStr find whole string, not part of it

I'm trying to make a login/register system.
This is the registration UserForm.
Private Sub regReg_Click()
Dim TextFile As Integer
Dim FilePath As String
If regAParole.Text = "aparole" Then
FilePath = ThisWorkbook.Path & "\accounts.txt"
TextFile = FreeFile
Open FilePath For Append As #1
Print #TextFile, regID; regAmats; regParole
Close TextFile
MsgBox ("Registracija veiksmiga.")
Unload Registracija
Else
MsgBox ("Nepareiza administratora parole.")
End If
End Sub
The "aparole" thing is basically just a keyword to enter in a field so only administrators can create new accounts.
accounts.txt content looks like:
1DirectorPassword (ID+jobposition+password)
This is the authentication:
Private Sub logAuth_Click()
Dim TextFile As Integer
Dim FilePath As String
Dim FileContent As String
Dim find As String
Dim result As Integer
find = logID & logAmats & logParole
FilePath = ThisWorkbook.Path & "\accounts.txt"
TextFile = FreeFile
Open FilePath For Input As TextFile
FileContent = Input(LOF(TextFile), TextFile)
result = InStr(FileContent, find)
If result >= 1 Then
MsgBox ("Autorizacija veiksmiga!") ' Success
Unload Autorizacija
End If
Basically when logging in I search within the accounts.txt for the string combo (ID+jobposition+password) which I use when registering. So in general the approach works, but:
If I enter everything perfectly matched = works great
If I enter the password half of it, like in a format of = 1DirectorPass it still works, so basically how can I tell to only search for the whole string and not parts of it?
I think the issue lies within InStr...
You could test for the newline markers in your file content, like this:
result = InStr(vbCrLf & FileContent, vbCrLf & find & vbCrLf)
This will only match complete lines. An extra newline is added before the file content so also the first line can be matched. At the end of the file content you would already have a vbCrLf character, because Print is supposed to add that.

VBA excel: how to add text to all files on a folder

I need to add text string to all files on a folder, as a footer
For example, on the folder on the path and called C:\mobatchscripts\
I have a random number of txt files, with text.
I want to add a line for example "text" on each of the text files on the folder
I have little knowledge of vba programming, but for what I have read I can use append, but I need something that loop on the files on the folder, and modify them.
So far I tried this:
Sub footer()
Dim FolderPath As String
Dim FileName As String
Dim wb As Excel.Workbook
FolderPath = "C:\mobatchscripts\"
FileName = Dir(FolderPath)
Do While FileName <> ""
Open FileName For Append As #1
Print #1, "test"
Close #1
FileName = Dir
Loop
End Sub
But seems that its not looking into the files, or appending the text.
On the assumption that you're writing to text files (I see "batchscripts" in the path), you need a reference to the Microsoft Scripting Runtime (Within the VBE you'll find it in Tools, References)
Option Explicit
Public Sub AppendTextToFiles(strFolderPath As String, _
strAppendText As String, _
blnAddLine As Boolean)
Dim objFSO As FileSystemObject
Dim fldOutput As Folder
Dim filCurrent As File
Dim txsOutput As TextStream
Set objFSO = New FileSystemObject
If objFSO.FolderExists(strFolderPath) Then
Set fldOutput = objFSO.GetFolder(strFolderPath)
For Each filCurrent In fldOutput.Files
Set txsOutput = filCurrent.OpenAsTextStream(ForAppending)
If blnAddLine Then
txsOutput.WriteLine strAppendText
Else
txsOutput.Write strAppendText
End If
txsOutput.Close
Next
MsgBox "Wrote text to " & fldOutput.Files.Count & " files", vbInformation
Else
MsgBox "Path not found", vbExclamation, "Invalid path"
End If
End Sub
I'd recommend adding error handling as well and possibly a check for the file extension to ensure that you're writing only to those files that you want to.
To add a line it would be called like this:
AppendTextToFiles "C:\mobatchscripts", "Test", True
To just add text to the file - no new line:
AppendTextToFiles "C:\mobatchscripts", "Test", False
Alternatively, forget the params and convert them to constants at the beginning of the proc. Next time I'd recommend working on the wording of your question as it's not really very clear what you're trying to achieve.

Can I use a variable to name other variables?

I'm working on some code that requires lots of data to be stored and I want to write a new data type for these to be placed into.
Private Sub CommandButton1_Click()
Dim myFile As String, text As String
myFile = Application.GetOpenFilename()
Open myFile For Input As #1
Do Until EOF(1)
Line Input #1, text
'Check to see if line contains name
If InStr(text, "name=") <> 0 Then
'Trim down to just name
text = Replace(text, "name=", "")
text = Trim(text)
'Set the current value of text as name of new scalarIn
Dim text As scalarIn
End If
Loop
End Sub
I don't think this works but its more to help understand the idea. What I want to happen is to read in a name from a file and set it as the name of a new instance of my custom data type.
Public Type scalarIn
UnitOfMeasure As String
Value As Variant
Source As String
End Type