Dynamically importing text from txt file in Word VBA - vba

So I have a text file with certain keywords, one on each line, which need to be imported into VBA. The keywords will be used in a find loop to check other documents. For this, I used this explanation: https://www.techrepublic.com/article/macro-trick-how-to-highlight-multiple-search-strings-in-a-word-document/ . However it is not robust as the words are hardcoded and the size of the list of keywords needs to be defined a priori.
So what I now have done is import the txt file in Word VBA, first counted all the lines, set the size of the keyword list and then looped again over the text file whilst trying to define each index of the keyword list. However the last bit fails. Using F8 I double checked that the code got the right word, but the "keywordlist(i) = textline" does not seem to actually parse the text string to the list.
What is going wrong here?
sub getkeywords
On Error Resume Next
MsgBox "Select text file with keywords."
On Error GoTo 0
Dim keyfile As String, textline As String
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
.Title = "Select Text Files"
.Filters.Clear
.Filters.Add "Text files", "*.txt"
.InitialView = msoFileDialogViewDetails
.Show
On Error Resume Next
keyfile = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End With
Open keyfile For Input As #1
Dim i As Integer
Do Until EOF(1)
Line Input #1, textline
i = i + 1
Loop
Dim j As Integer
j = i - 1
Dim keywordlist() As String
ReDim keywordlist(0 To j) As String
i = 0
Do Until EOF(1)
Line Input #1, textline
keywordlist(i) = textline
i = i + 1
Loop
Close #1
end sub

I found the error. After the first Do Until loop, the code neglects the file and hence the second Do loop is not executed. A simple fix was to place Close #1 and Open #1 before the second loop. May not be pretty but it works.

Related

Error 53 when opening CSV file on mac

When I try and open a CSV file, I get:
Error 53: File not found
I get the error on the 4th line, Open FilePath For Input As #1
What am I doing wrong?
It is my first time opening a CSV, please be indulgent with my code.
Sub opentextfile()
Dim FilePath As String
FilePath = "/Users/christinekelly/Desktop/authors.csv"
file1 = FreeFile
Open FilePath For Input As #file1
row_number = 0
Do Until EOF(1)
Line Input #file1, LineFromFile
LineItems = Split(LineFromFile, ",")
ActiveCell.Offset(row_number, 0).Value = LineItems(2)
ActiveCell.Offset(row_number, 1).Value = LineItems(1)
ActiveCell.Offset(row_number, 2).Value = LineItems(0)
Number = row_number + 1
Loop
Close #file1
End Sub
So from looking at #Rebekare's answer to this question this is what worked for me.
I went to the file in question test.csv and opened the immediate window and typed ?ThisWorkbook.Path and got HDD:Users:USER:Desktop.
I then used the suggested concatenatation of this path with Application.PathSeparator & filename i.e.
FilePath = "HDD:Users:USER:Desktop" & Application.PathSeparator & "test.csv"
This is a useful approach as you get the actual file path syntax and then yield the path separator decision to the Application.
Following on from #Mat'sMug suggestion, I found this, which opens the file dialog, and you select the file you want the full path of and it is returned via the message box.
Sub PathofFile()
OpenFile = Application.GetOpenFilename()
MsgBox OpenFile
End Sub
Within that same link was a suggestion for using the Dir function to test if the filepath is valid. If valid you get the filename back, if not you get an error which you can use to determine your next action e.g. the following returns "test.csv" if it exists at that filepath.
MsgBox Dir("HDD:Users:USER:Desktop:test.csv")
If you are doing other operations with the file you might want to add a test to to see if the file is open first, using Microsoft's IsFileOpen function. An example as follows:
Sub Test
If Not IsFileOpen(FilePath) Then
Set wb = Workbooks.Open(FilePath)
End If
End Sub
Function IsFileOpen(filename As String)
Dim filenum As Integer, errnum As Integer
On Error Resume Next ' Turn error checking off.
filenum = FreeFile() ' Get a free file number.
' Attempt to open the file and lock it.
Open filename For Input Lock Read As #filenum
Close filenum ' Close the file.
errnum = Err ' Save the error number that occurred.
On Error GoTo 0 ' Turn error checking back on.
' Check to see which error occurred.
Select Case errnum
' No error occurred.
' File is NOT already open by another user.
Case 0
IsFileOpen = False
' Error number for "Permission Denied."
' File is already opened by another user.
Case 70
IsFileOpen = True
' Another error occurred.
Case Else
Error errnum
End Select
End Function

Search or compare value in the textbox in certain folder or directory(location) and list the log file which have the exact value in it

[Hi All I am just new in VBA excel macro and trying to create my own macro. the vb mini-program i have will search for specific value(example. 15) in all the log files in certain directory or location. Once the value was found in the log file, the program will list it in list box. my program is functioning. My only problem is, if theres hundreds or thousands of log files in the location, the program will list all log data with value of 1 or 5 including the log data with the exact value 15. the other problem is that the log data with value of 15 will be listed below which is supposed to be on the top or listed at the first found item which have the correct value. Below are my questions.
Is it possible that if the program found out the log data with exact value, the program will list it on top or can be listed first?
It is more easy also if the output will be limit . Because if there are thousands or hundreds of file with 1 and 5 , everything will be listed in the list box. is it possible to list only the right log data with value of 15? Kindly see below snapshot and code. I am planning to use this macro also in my work the reason why I am trying to figure it out.
Program:
Private Sub Comfind_Click()
Dim theString As String
Dim path As String
Dim StrFile As String
Dim fso As New FileSystemObject
Dim file As TextStream
Dim line As String
Dim blnFound As Boolean
ListLog.Clear
theString = TextPlate.Text
path = TextPath.Text
StrFile = Dir(path & "*.pdms")
Do While StrFile <> ""
'Find TheString in the file
'If found, list log and exit loop
Set file = fso.OpenTextFile(path & StrFile)
Do While Not file.AtEndOfLine
line = file.ReadLine
If InStr(1, line, theString, vbTextCompare) > 0 Then
ListLog.AddItem StrFile
Exit Do
End If
Loop
file.Close
Set file = Nothing
Set fso = Nothing
StrFile = Dir()
Loop
MsgBox "successfully search log data!!!"
End Sub
Log file:
You can narrow it down a bit:
Dim arr
Do While Not file.AtEndOfLine
line = file.ReadLine
If InStr(1, line, "PLATEKEY", vbTextCompare) > 0 Then
arr = Split(line, "PLATEKEY")
If Trim(arr(1)) = theString Then
ListLog.AddItem StrFile
Exit Do
End If
End If
Loop

How to catch error "File not loaded completely"

I have a code which opens a text file. It contains a number of rows that is more than the limit of Excel. When manually opening it, there is a prompt that says "File not loaded completely" but when in macro, I don't see a prompt.
What I want to do is to catch that error. Even when the display alerts of my macro is enabled, still no error is caught.
On Error Goto catch_err
...open text file here
On Error Goto 0
catch_err:
Msgbox err.description
That is the structure of my code.
Why don't you stream the file in and move to the next tab every time you hit 1M rows?
I threw this together for you, excuse the Citrix line in there (I needed it for testing, left it in in case you are on that environment).
Sub BigFile()
Dim myFile As String, textline As String, X As Long
'myFile = "\\Client\C$\Temp\YourBigFile.txt" 'Silly Citrix syntax
myFile = "C:\Temp\YourBigFile.txt" 'Normal syntax
Open myFile For Input As #1
Do Until EOF(1)
X = X + 1
If X = 1000000 + 1 Then
Sheets.Add
X = 1
End If
Line Input #1, textline
Range("A" & X).Formula = textline
Loop
Close #1
End Sub
This way you don't need to test for the error because there won't be one.

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

PowerPoint VBA: open a text file and show each line on a seperate slide

I want PowerPoint to open an external text file and show line 1 of this file on slide 1 of my presentation, line 2 on slide 2, etc.
If the number of slides is larger than the number of lines in the text file, I would like to start at line 1 again.
Here's what I have so far (mixed code and pseudocode):
Dim FileName, FSO, MyFile
FileName = "C:\test.txt"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set MyFile = FSO.OpenTextFile(FileName, 1)
For i = 1 To ActivePresentation.Slides.Count
If LINE(i) EXISTS IN TEXT FILE THEN
ActivePresentation.Slides(i).Shapes("myshape").TextFrame.TextRange.Text = LINE(i)
ELSE START AT LINE(1) AGAIN
End If
Next
MyFile.Close
How do I refer to the lines in the text file using i, and what would be the best way to do the if/then-statement?
Your help would be greatly appreciated!
Please understand I cannot do the whole thing for you but the logic somehow looks like this:
MoreSlides = true
While moreSlides
Open "mytextfile.txt" For Input As 1
While Not EOF(1) and moreSlides
Line Input #1, myline
' here comes the part inserting the line in the next slide
' You set moreSlides to false if you reach the end
Wend
close #1
Wend