简体   繁体   中英

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?

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.

You can also call notepad++ with the "-n" argument for the same effect,

Sending keys (specially with delays) might be a dangerous thing if you switch screens or a popup window appears while the command is executing you might lose data or inadvertly execute a dangerous action in that other application.

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