Can somebody let me know how in Word doc can a word be searched and then get Nth word in that line(found text line), using VB??

Dani AI

Generated

Building on 's tip to inspect the raw file, the most reliable approach is to treat the log as plain text and parse each physical row yourself (Word's visual "line" will wrap long rows and confuse extraction). Two simple VBA options follow: (A) read the .txt/.csv file line-by-line and Split the row into fields (recommended for tab/CSV logs); (B) if each log row is already a true Word paragraph, find the paragraph containing your search term and split that paragraph.

Macro A — read file and get the Nth field (recommended)

  • Set fName to your log path, searchFor to the string you look for, and N to the field index you want.
  • The macro auto-detects tab/comma/space and normalizes whitespace.
Sub GetNthFieldFromFile()
  Dim fName As String: fName = "C:\path\log.txt"
  Dim searchFor As String: searchFor = "STATE"
  Dim N As Long: N = 5
  Dim tline As String, F As Integer: F = FreeFile
  Open fName For Input As #F
  Do While Not EOF(F)
    Line Input #F, tline
    If InStr(1, tline, searchFor, vbTextCompare) > 0 Then
      Dim delim As String
      If InStr(tline, vbTab) > 0 Then delim = vbTab ElseIf InStr(tline, ",") > 0 Then delim = "," Else delim = " "
      If delim = " " Then
        Dim re As Object: Set re = CreateObject("VBScript.RegExp")
        re.Pattern = "\s+": re.Global = True
        tline = re.Replace(Trim(tline), " ")
      End If
      Dim parts() As String: parts = Split(tline, delim)
      If UBound(parts) >= N - 1 Then Debug.Print Trim(parts(N - 1)) Else Debug.Print "(no field)"
    End If
  Loop
  Close #F
End Sub

Macro B — operate on a paragraph that contains the search text

  • Useful only when each log row is a single paragraph in Word. This finds the paragraph, normalizes whitespace, and selects the Nth token.
Sub SelectNthWordInParagraphContaining()
  Dim findText As String: findText = "STATE"
  Dim N As Long: N = 5
  Dim rng As Range: Set rng = ActiveDocument.Content
  With rng.Find
    .Text = findText: .Wrap = wdFindStop
    If .Execute Then
      Dim p As String: p = rng.Paragraphs(1).Range.Text
      p = Replace(p, vbCr, ""): p = Replace(p, vbTab, " ")
      Dim re As Object: Set re = CreateObject("VBScript.RegExp")
      re.Pattern = "\s+": re.Global = True: p = re.Replace(Trim(p), " ")
      Dim words() As String: words = Split(p, " ")
      If UBound(words) >= N - 1 Then
        Dim startOffset As Long, i As Long
        For i = 0 To N - 2: startOffset = startOffset + Len(words(i)) + 1: Next i
        Dim selRng As Range: Set selRng = rng.Paragraphs(1).Range
        selRng.Start = selRng.Start + startOffset
        selRng.End = selRng.Start + Len(words(N - 1))
        selRng.Select
      End If
    End If
  End With
End Sub

Notes and troubleshooting

  • If the file uses quoted CSV, embedded delimiters, or non-ANSI/UTF-8 encoding, use a proper CSV parser or ADODB.Stream; simple Split will fail on quoted fields.
  • If Word visually splits rows across lines, do not rely on Word layout — use Macro A to preserve original rows.
  • Use a hex/text viewer (Notepad++ or similar) to confirm actual delimiters and newline characters before parsing.

Recommended Answers

All 3 Replies

Ive had a similar problem to sort out. First get yourself a RAW TEXT notepad type program, I use Textpad, it shows ALL characters, including the ones under CHR(32). This will give you a general text space layout and some idea on what to search for and where.

Doc files contain loads of data per file to cope with tables, margins, fonts etc. Once you have looked at a few test documents youll have an idea what to look for.

After that its just a case of INSTR search for what you want and scan the SPACES back to the start of the line. Do it on a line scan principal and it doesnt get confusing.

Diguelo,
Can you make your reply more clear.
I dont get a clear picture on how to search for a string in Notepad. Ideally i too have to view the data(tab seperated logged values) in notepad as they are around 80 different parameter values logged per sec(80 col per row). I need to search for a state( string) and then look for some parameters in that row(of that time stamp). when i try to open this text file in MS Word, each row(with 80 col) gets split across 6 lines. How do i do this with notepad/csv?

I wouldnt bother with comma seperated values type data handling as the commas may need to be sent in your datastream as part of a block.

I meant to have said if you use a notepad type program to first analyse your document to get your program scanning correct as in make a test document and see what does what to a rich text environment document. As in make a doc file, open it in notepad or similar and see what is actually in it and how changes affect data positions within the file.

Once you have a full idea on whats going on then all you need do is if say the first 100 characters of a doc file are for the tab table, font list etc then you can either skip them or search for the details.

Once you have an idea where to look in the file for what your after then its relatively easy to use a search string and Instr system to get out all relevant information.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.