Open and Close Folder or File with VB or VBA

Thursday, July 29, 2010 by Tan
Hi Folks!

There are two new things that I learnt while coding in VBA today and I thought of sharing the same with you!

Ever wanted to open a directory or folder somewhere in the computer from within the code you write? Well, some you might have wondered how to do that; and to others, who have not tried it, it would sound rather interesting. Here is one way that you can do this. To open a folder called Code present in your C Drive, you can use the following code:

Sub OpenDir()
Call Shell("Explorer C:\Code, vbNormalNoFocus)

Yea, that is all it is! Simple, right? I felt so, after some good time spent on it.

Here is the next one. We all use Alt + F4 to close a file, a folder, Windows Sessions or even the application that we are working on. How to do that from within your script? Well, here we are trying to replicate the key press combination: Alt + F4; and not just a close syntax. Heard of the command SendKeys? Here is one way to do that:

Sub PressKey()
SendKeys "%{F4}"

Or if you want a question before you close:

Sub PressKey()
Dim iX As Integer
iX = MsgBox("Close?", vbQuestion)
If iX = vbOK Then
SendKeys "%{F4}"
End If

Hmmm. I found it interesting! Go ahead and try different things with SendKeys and I am sure you will discover something more, for sure. Also, let us know if you have some specific queries related to the above two commands. We will try to dig into it. Keep coding – keep learning and do not forget to share what you have got.

Let us learn and grow together!
Posted in Labels: , , , | 0 Comments »

0 Reviews: