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

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.

Related

Execute With...End With Statement in Immediate window, Excel VBA

I'm trying to execute With...End With Statement in the Immediate Window,
but I'm not getting it to work.
So my question is how do you execute multiple line of Code concerning With...End With Statement in the Immediate window?
My code I'm trying to execute in the Immediate window:
With Date_Per_Month.Range("A2:H32")
.Offset(1).Resize(.rows.Count - 1, .Columns.Count - 1).select
end with
Ofcourse it works to write a single line of code like this in the immediate window (but that doesn't answer the question).:
Date_Per_Month.Range("A2:H32").Offset(1).Resize _(Date_Per_Month.Range("A2:H32").Rows.Count-1,Date_Per_Month.Range("A2:H32").Columns.Count-1).Select
Tried to concatenate each code line with ":" at the end of lines but it didn't work.
Any help is highly appreciated.
The immediate toolwindow is essentially a console. You can use it to evaluate expressions without an execution context, or in break mode in the context of the current procedure.
Each "line" can be [almost] any executable instruction, but
You can assign to a variable that doesn't exist...
foo = 42
...and then this identifier exists in the "immediate" context and you can use it in subsequent statements:
?TypeName(foo)
Integer
...until you explicitly reset that context:
End
?TypeName(foo)
Empty
But you can't declare a variable:
Dim foo
A With statement is special: it witholds an object reference, but syntactically it's a block statement that needs to be terminated with an End With token: if you try to type With Sheet1 in the immediate pane, you'll get a compile error saying End With is missing - again because each statement in the immediate pane is a standalone instruction.
We could try to inline it:
With Sheet1 : .Cells(1, 1).Value = 42 : End With
But then we get a weird "invalid watch expression" error:
Regardless of the reason, like declaring variables with a Dim statement, defining a With variable makes no sense in the context of the immediate pane, where the next instruction to run is whatever instruction you happen to hit ENTER on: there's no scope, no sequence of operations - an instruction runs immediately, and that's all: whatever the contents of the immediate pane is, no other instruction will run until you hit ENTER on it.
how do you execute multiple lines of code [...] in the Immediate window?
The answer is, you don't - because the immediate toolwindow has no concept of "lines of code".

Opening a File whose Name Contains a Space

I have some simple Excel VBA code that opens non-Excel files like:
Sub scriptTest()
Set objshell = CreateObject("Wscript.Shell")
objshell.Run ("C:\TestFolder\Book1.pdf")
Set objshell = Nothing
End Sub
Running this opens the file in the Acrobat Reader. However if I try to open a file whose name contains a space character like:
Sub scriptTest()
Set objshell = CreateObject("Wscript.Shell")
objshell.Run ("C:\TestFolder\Bo ok1.pdf")
Set objshell = Nothing
End Sub
I get:
Both files open fine if I use the Run command from the Windows Start menu. How can I overcome this problem ??
When executing the statement objshell.Run ("C:\TestFolder\Bo ok1.pdf"), you are asking the shell to execute the command
C:\TestFolder\Bo ok1.pdf
This is interpreted as being a request to execute the program C:\TestFolder\Bo.exe with a parameter of ok1.pdf.
You actually want the shell to execute the command
"C:\TestFolder\Bo ok1.pdf"
where the quotation marks are used by the command interpreter to "group" parts of the command together.
To obtain that command, you need to execute the statement
objshell.Run """C:\TestFolder\Bo ok1.pdf"""

How to update applescript to open txt files in vim in iTerm3

For years I've been using the following AppleScript to open txt files in vim in iTerm2, but since iTerm 2.9.2 (aka iTerm3) it's broken. Could anyone advise how to update this AppleScript so it works again?
on run {input, parameters}
if (count of input) > 0 then
tell application "System Events"
set runs to false
try
set p to application process "iTerm"
set runs to true
end try
end tell
tell application "iTerm"
activate
if (count of terminals) = 0 then
set t to (make new terminal)
else
set t to current terminal
end if
tell t
tell (make new session at the end of sessions)
exec command ("vim \"" & POSIX path of first item of input as text) & "\""
end tell
if not runs then
terminate first session
end if
end tell
end tell
end if
end run
I originally copied the script from http://earthwithsun.com/questions/283418/how-can-i-make-terminal-vim-my-default-editor-application-in-mac-os-x but I have no AppleScript experience whatsoever.
Any help most appreciated!
B
Using #dusty's link, I recommend that you change the entire code section of your Run AppleScript Action to this:
on run {input, parameters}
tell application "iTerm"
activate
if (count of windows) = 0 then
set t to (create window with default profile)
else
set t to current window
end if
tell t
tell current session
write text ("vim \"" & POSIX path of first item of input as text) & "\""
end tell
end tell
end tell
end run
It seems to work on my machine, but I never use vim, so I am not sure if this will give you precisely what you want.
Good luck,
The new Applescript syntax doesn't have terminal as a top-level object like before. It has been changed to reflect more of the common pattern used throughout the OS for other scriptable applications: the top-level objects of the application are called windows, not terminals.
So the hierarchy is now something like this:
the application containing one or more
windows containing one or more
tabs containing a
session
https://iterm2.com/applescript.html has been updated with examples of the new syntax.
I adopted the code snippet of Craig Smith (great answer!) and tweaked it a little to open a new tab if there is already an open window. This way, you don't get any trouble if you have already something like vim opened in your iTerm. Also, this code changes the directory to the directory of the file to make NerdTREE and fuzzy finders like fzf.vim happy.
on run {input, parameters}
set filename to POSIX path of input
set cmd to "clear; pushd " & quote & "$(dirname " & filename & ")" & quote & " > /dev/null; nvim " & quote & "$(basename " & filename & ")" & quote & "; popd > /dev/null"
tell application "iTerm"
activate
if (count of windows) = 0 then
set t to (create window with default profile)
else
set t to current window
tell t
create tab with default profile
end tell
end if
tell t
tell current session
write text cmd
end tell
end tell
end tell
end run
I took inspiration in the previous anwers and made a few extensions.
My solution accepts multiple input files (e.g. from a selection).
If there is an active window, the script searches for open vim sessions in any of the tabs and opens the files inside of that vim instance. If there are none, it creates a new iTerm tab or window.
on run {input, parameters}
set vimCommand to "nvim -p "
tell application "iTerm"
activate
if (count of windows) = 0 then
set w to (create window with default profile)
else
set w to current window
try
# raises error when all windows are minimized
tell w
# look for tab with open vim session
repeat with t in tabs
tell t
if name of current session contains "vim" then
# open files in current vim session
set esc to character id 27
tell current session
write text (esc & esc & ":silent! tablast")
repeat with filename in input
set filePath to quoted form of POSIX path of filename
write text (":execute 'tabedit '.fnameescape(" & filePath & ")")
end repeat
select
end tell
select
return
end if
end tell
end repeat
# no existing session
create tab with default profile
end tell
on error msg
set w to (create window with default profile)
end try
end if
# open in new tab or window
tell w
tell current session
set launchPaths to ""
repeat with filename in input
set filePath to quoted form of POSIX path of filename
set launchPaths to launchPaths & " " & filePath
end repeat
write text (vimCommand & launchPaths)
end tell
end tell
end tell
end run
Something like this in Automator:
on run {input, parameters}
set vim_par to POSIX path of input
set cmd to "/usr/local/bin/vim " & quote & vim_par & quote
tell application "iTerm"
tell current window
create tab with default profile command cmd
end tell
end tell
end run
Save as .app, and then open files via it -- probably, make that .app a default "Open with" app.

Apple Script won't display line breaks

Making a small script to connect me to the console on some cisco equipment via a usb to serial connection in terminal.
However I am finding it impossible to put line breaks or returns in between the text and Variables (like using <br> in HTML).
So in the display dialog line all the text comes out all mashed together.
I have tried using \n , \ \n, changing the preferences to Formatting > escape tabs and line Breaks in strings > Checked.
So any help would be much appreciated.
set theFind to "ls /dev/tty.*"
set theResult to do shell script theFind
set theConnection to text returned of (display dialog "Serial interface to availble:" & theResult & "Interface to use:" default answer "/dev/tty.usbserial")
tell application "Terminal"
activate
tell application "System Events"
delay 1
keystroke "screen " & theConnection & " 9600"
keystroke return
beep
end tell
end tell
AppleScript doesn't use linefeeds as line breaks (as unix generally does), it uses carriage returns. You can translate them with tr '\n' '\r' (suitably escaped, of course). Also, you'll need to manually add returns before & after the included output; for some bizarre reason, AppleScript uses \n for that instead of \r. Here's the net result:
set theFind to "ls /dev/tty.* | tr '\\n' '\\r'"
set theResult to do shell script theFind
set theConnection to text returned of (display dialog "Serial interface to availble:\n" & theResult & "\nInterface to use:" default answer "/dev/tty.usbserial")
tell application "Terminal"
activate
tell application "System Events"
delay 1
keystroke "screen " & theConnection & " 9600"
keystroke return
beep
end tell
end tell

Calling single/bunch of statements from within VIM on Windows

I am totally new to Vim and just two days into learning it. Like every Vim user I am deeply impressed by the speed boost it has given me.
I create Windows batch(.bat) files with numerous call statements. Usually I run a single call statement with Run prompt and use a .bat file for a set of statements. This is done to ensure that the statements provide desired results. I read that it is possible to run similar scenarios from within Vim. Here are some sample statements which form a part of my batch file:
A single line statement:
call %VT_BATCH_ROOT%\Menu\Sub-menu\Name "Line Geometry" "" "" "OK"
A multi-line scenario:
call %VT_BATCH_ROOT%\Menu\Sub-menu\Command "Yes" "c:\temp\folder\file.ext"
call %VT_BATCH_ROOT%\Menu\Sub-menu\Command "No"
call %VT_BATCH_ROOT%\Menu\Sub-menu\Command "Yes" "" "c:\temp\folder\file.ext" "" "" ""
Can someone suggest me how can my requirements be achieved?
I'm not sure if this is what you're asking, but you can use :! to execute a shell command. For example, type :!dir to open a shell and list the current directory. If you already have the command you want to run open as part of the file you are editing, you could copy and paste it in this way.
Edit: To execute the current line as a shell command in Windows, you can do :.w !cmd -. For multiple lines, you could record a macro that did this and then moved to the next line, and execute the macro as many times as necessary.

Resources