A Simple VB Utility Program Tutorial: To copy out lines from a text file based on a line word search – like grep. This example searches for all “QUAD” elements in a Nastran deck and writes them to Out.txt

1) Follow steps 1 to 4 in tutorial 1 to add a command button to the worksheet

2) The code :-

Option Explicit

‘This procedure copies all the lines from a Nastran deck

‘with the keyword QUAD in it to “C:\Out.txt”

‘The input could be any text file

‘And the keyword could be anything

‘This is similar thing to the unix grep command

Private Sub CommandButton1_Click()

Dim FileName2Open As String

Dim iFile As Integer

Dim iFile2 As Integer

Dim sLine As String

iFile2 = FreeFile                                       ‘Get a free file number

Open “Out.txt” For Output As iFile2           ‘open a file to write the striped lines to

FileName2Open = Application.GetOpenFilename(“Dat Files (*.*), *.dat”)      ‘Get the file name to search

If FileName2Open <> “False” Then

  iFile = FreeFile

  Open FileName2Open For Input As iFile    ‘Open this file

  Do Until EOF(iFile)

    Line Input #iFile, sLine                           ‘Read every line until the end of the file

    If InStr(1, sLine, “QUAD”) Then              ‘if the line has “QUAD” in the text

       Print #iFile2, sLine                              ‘print the line to “C:\Out.txt”

    End If

  Loop

  Close #iFile

End If

Close #iFile2

End Sub

If you open Out.txt in notepad it should contain all the lines which contain the “QUAD” search word which were in the selected file.

The next tutorial creates a group of elements from an Excel listing of IDs. This is a useful utility to be able to easily identify certain elements.