简体   繁体   English

如何使用VBA在特定行打开和显示文本文件?

[英]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: 我有一个VBA用户窗体,可使用以下命令在TextPad中打开文本文件:

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? 有没有办法将行号作为参数传递给此Shell调用?

You can accomplish this using WScript.Shell.SendKeys to trigger the goto line shortcut within TextPad (ctrl-G) 您可以使用WScript.Shell.SendKeys在TextPad(ctrl-G)中触发goto行快捷方式来完成此操作

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. 您可能必须弄乱“等待”行才能添加或删除命令之间的延迟,但是我在Excel中的VBA模块中对此进行了测试,并且可以正常工作。

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. 我知道可以直接从VBA调用SendKey,但是当我尝试使用它时,它似乎绑定到了vba编辑器窗口。

You can also call notepad++ with the "-n" argument for the same effect, 您也可以使用“ -n”参数调用notepad ++,以获得相同的效果,

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. 如果在执行命令时切换屏幕或出现弹出窗口,则发送键(特别是延迟)可能是危险的事情,这可能会丢失数据或在其他应用程序中无意中执行危险的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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