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

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

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.

How to Convert .csv into .txt for Matlab Import

I have a .csv file. I want to convert it into .txt file starting from line the A to the B (A, B are declared at the beginning). The .txt file supposed to have gaps " " instead of original semicolons. Moreover, the end of each copied row from the original .csv file should be indicated by a semicolon in the new .txt file (txt file is going to be used as an input matrix for Matlab).
That's what I have till now, but it's not working
Sub csv2mat()
Dim Filename As String
Dim Filenamenew As String
'Change the path to the Files and and create a txt file
Filename = "C:\Documents and Settings\user\Desktop\as.csv"
Filenamenew = "C:\Documents and Settings\user\Desktop\new.txt"
Open Filenamenew For Output As #2
Open Filenamme For Input As #1
Do While Not EOF(1)
Line Input #1, str
str = Replace(str, ";", """")
Print #2, str
Loop
End Sub
You hade a few spelling mistakes like Filnemme with to m.
And you forgot to close the Files after Reading.
And you didn't add the ";" ad the and of the string if i understand you right
Try this:
Sub csv2mat()
Dim Filename As String
Dim Filenamenew As String
Dim str As String
'Change the path to the Files and and create a txt file
Filename = "C:\Documents and Settings\user\Desktop\as.csv"
Filenamenew = "C:\Documents and Settings\user\Desktop\new.txt"
Open Filenamenew For Output As #2
Open Filename For Input As #1
Do While Not EOF(1)
Line Input #1, str
str = Replace(str, ";", """") & ";"
Print #2, str
Loop
Close #1
Close #2
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.

How to change section text in INI file using Word 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

How to read a big file list from a textfile to form a query

I have this query which I have to run multiple times in excel and i need to change the filelists in it.
select * from files
where
filename in ('filename1','filename2')
so I have a TEMP in my query filename in TEMP and I want to loop and get the result for all filelists. My onlyproblem is reading .txt into the TEMP and executing the query once for all filenames in the txt file. i know how to read files line by line so that didn't help.
my text files which I want to read the lists from are like
filename1
filename2
.
.
.
.
filename15000
yes some big numbers.
dim filelist as string
dim filelistpath as string
sqlstring = "select count(*) from files where filename in TEMP"
filelistpath = "c:\"
open filelistpath for input as #1
do while not EOF(1)
line input #1,text
'here i should construct my file list to replace the TEMP below, how ?
loop
close #1
sqlstring = replace(sqlstring,TEMP, filelist)
set rs = conn.execute(sqlstring)
'here i want to write the result to my excel sheet, how ?
thanks
I formatted the text and just read it like that as a whole
Function GetText(sFile As String) As String
Dim nSourceFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nSourceFile = FreeFile
''Write the entire file to sText
Open sFile For Input As #nSourceFile
sText = Input$(LOF(1), 1)
Close
GetText = sText
End Function