Thursday, June 25, 2009

Code to open all files(excel) from a specific folder using comman dialog box.


'************** Code Start **************

'It is not to be altered or distributed,
'except as part of an application.
'You are free to use it in any application,
'provided the copyright notice is left unchanged.
'
'Code courtesy of
'www.ammara.com
 
Private Type BROWSEINFO
  hOwner As Long
  pidlRoot As Long
  pszDisplayName As String
  lpszTitle As String
  ulFlags As Long
  lpfn As Long
  lParam As Long
  iImage As Long
End Type
 
 
Private Declare Function SHGetPathFromIDList Lib "shell32.dll" Alias _
            "SHGetPathFromIDListA" (ByVal pidl As Long, _
            ByVal pszPath As String) As Long
           
Private Declare Function SHBrowseForFolder Lib "shell32.dll" Alias _
            "SHBrowseForFolderA" (lpBrowseInfo As BROWSEINFO) _
            As Long
           
Private Const BIF_RETURNONLYFSDIRS = &H1
Public Function BrowseFolder(szDialogTitle As String) As String
  Dim X As Long, bi As BROWSEINFO, dwIList As Long
  Dim szPath As String, wPos As Integer
 
    With bi
        .hOwner = hWndAccessApp
        .lpszTitle = szDialogTitle
        .ulFlags = BIF_RETURNONLYFSDIRS
    End With
   
    dwIList = SHBrowseForFolder(bi)
    szPath = Space$(512)
    X = SHGetPathFromIDList(ByVal dwIList, ByVal szPath)
   
    If X Then
        wPos = InStr(szPath, Chr(0))
        BrowseFolder = Left$(szPath, wPos - 1)
    Else
        BrowseFolder = vbNullString
    End If
End Function
 
Sub openAllfilesInALocation()
Dim i As Integer, wb As Workbook
fldname = BrowseFolder("Choose Folder For Import")
If Len(fldname) > 0 Then
        ' Do something with the selected folder
    Else
       
        MsgBox "No folder/Directory selected"
        End
    End If
With Application.FileSearch
.NewSearch
.LookIn = fldname
.SearchSubFolders = False
.Filename = "*.csv"
.Execute
For i = 1 To .FoundFiles.Count
'Open each workbook
Set wb = Workbooks.Open(Filename:=.FoundFiles(i))
'Perform the operation on the open workbook
Range("A1") = Date
'Save and close the workbook
wb.Close savechanges:=True
'On to the next workbook
Next i
End With
End Sub

'************** Code End **************


ICC World Twenty20 England '09 exclusively on YAHOO! CRICKET

No comments:

Post a Comment