简体   繁体   中英

Dynamically importing text from txt file in Word 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM