excelvbatextpad

How to open and display text file at specific line using VBA?


I have a VBA userform to open a text file in TextPad with the following:

Call Shell("C:\Program Files\TextPad 5\TextPad.exe " & "C:\testfile.txt", vbNormalFocus)

I'd like the text file to be displayed at a specific line number.

Is there a way to pass the line number as an argument to this Shell call?


Solution

  • You can accomplish this using WScript.Shell.SendKeys to trigger the goto line shortcut within TextPad (ctrl-G)

    Dim wshshell
    Set wshshell = CreateObject("WScript.Shell")
    
    Call Shell("C:\Program Files\TextPad 5\TextPad.exe " & "C:\testfile.txt", vbNormalFocus)
    Application.Wait (10)
    wshshell.SendKeys "^g"      'ctrl-G
    Application.Wait (10)
    wshshell.SendKeys "15"      'desired line number
    Application.Wait (10)
    wshshell.SendKeys "{ENTER}" 'enter
    

    You might have to mess with the Wait lines to add or remove delays between commands, but I tested this from within a VBA module in Excel and it worked.

    I am aware that SendKeys that can be called directly from VBA, but when I tried to use that, it seems to be bound to the vba editor window.