Thursday, April 6, 2017

Excel VBA- Recursion Technique

There are a number of ways to copy files from one folder and its subfolders into another. For example, we can use the recursive function and FileSystemObject members to do it in VBA. But batch programming in DOS provides a very efficient technique to do the same. The following code illustrates this fact. In the below code, Shell function is used to execute the cmd command. ChDrive and ChDir are used to change drive and directory respectively.

Option Explicit

Sub pRecursiveCopy()


    Dim strCmdCommand As String


    ChDrive "E:"


    ChDir "E:\Ajeet"


    strCmdCommand = "cmd.exe /c FOR /R %f in (*.*) DO COPY " & """%f""" & " E:\Kumar"


    Shell strCmdCommand, vbHide


    MsgBox "Files copied from Ajeet folder into Kumar folder.", vbInformation, "Batch Code To Copy"


End Sub



Shell Function

It runs an executable program and returns a Variant (Double) representing the program's task ID if successful, otherwise it returns zero.

Syntax
Shell(pathname[,windowstyle])

The pathname is required and is Variant (String) datatype. It includes name of the program to be executed and any required argument or command line switches; and may include directory or folder and drive.

The windowstyle named argument has these values:



Constant
Value
Description
vbHide
0
Window is hidden and focus is passed to the hidden window. The vbHide constant is not applicable on Macintosh platforms.
vbNormalFocus
1
Window has focus and is restored to its original size and position.
vbMinimizedFocus
2
Window is displayed as an icon with focus.
vbMaximizedFocus
3
Window is maximized with focus.
vbNormalNoFocus
4
Window is restored to its most recent size and position. The currently active window remains active.
vbMinimizedNoFocus
6
Window is displayed as an icon. The currently active window remains active.

No comments:

Post a Comment

Hot Topics