Adding "Browse for folder' option for a merging macro - excel

I have under mentioned code for merging excel files into one workbook with multiple sheets. It works perfectly. I want some help to add "Browse for folder" function to this code. So, that user can choose which folder contain the source workbooks. Please help.
Sub Merge2MultiSheets()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFileName As String
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
MyPath = "C:\Jude" ' change to suit
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFileName = Dir(MyPath & "\*.xlsx", vbNormal)
If Len(strFileName) = 0 Then Exit Sub
Do Until strFileName = ""
Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFileName)
Set wsSrc = wbSrc.Worksheets(1)
wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
wbDst.Worksheets(wbDst.Worksheets.Count).Name = strFileName
wbSrc.Close False
strFileName = Dir()
Loop
wbDst.Worksheets(1).Delete
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
I tried the code below. But it gives error. Please look.
Function GetFolder(strPath As String, fldSt As String) As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = fldSt
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Sub Getsheets()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFileName As String
Path = GetFolder("C:\", "Select an Input Folder") & Application.PathSeparator
Set wbDst = Workbooks.Add(xlWBATWorksheet)
strFileName = Dir(Path & "*.xls?")
Do While Filename <> ""
Set wbSrc = Workbooks.Open(Filename:=Path & Filename, ReadOnly:=True)
Set wsSrc = wbSrc.Worksheets(1)
wsSrc.Copy After:=wbDst.Worksheets(wbDst.Worksheets.Count)
wbDst.Worksheets(wbDst.Worksheets.Count).Name = strFileName
wbSrc.Close False
strFileName = Dir()
Loop
wbDst.Worksheets(1).Delete
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub

Include:
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
and then in your Sub
MyPath = GetFolder
as a replacement for:
MyPath = "C:\Jude" ' change to suit

Related

Exception in file choosing

I wrote a macro. But now i want to run in on all files in folder which i choose, with exception of files named "Exception1.xlsx" and "Exception2.xlsx". I tried to do it but i am not sure how i can add exception to do while loop(if its right place). Do you have any suggestions?
Sub macro()
Dim ws As Worksheet
Dim Wb As Workbook
Dim strFolder As String
Dim strFil As String
Dim FldrPicker As FileDialog
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then Exit Sub
myFolder = .SelectedItems(1) & "\"
End With
strFolder = myFolder
strFil = Dir(strFolder & "\*.xls*")
Do While strFil <> vbNullString
Set Wb = Workbooks.Open(strFolder & "\" & strFil)
For Each ws In Worksheets
``my working code is here
Next ws
Wb.Save
Wb.Close False
strFil = Dir
Loop
End Sub
Thanks for all responses

Looping through excel files in a folder and performing a procedure on each of them VBA

My Aim:
This procedure is meant to loop through excel files in a specified folder and preform a sub (cleanDataAndTransfer), which is meant to clean the data in the files being looped through and then paste it in to a new sheet in the master file.
My problem:
Im getting the Run-time error '91': Object variable or With block variable not set on the .Title = "Select A Target Folder" line.
I've tried different solutions to rectify the issue but nothing has yet worked.
My code:
Sub loopAllExcelFilesInFolder()
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
myExtension = "*.xls*"
myFile = Dir(myPath & myExtension)
Do While myFile <> ""
Set wb = Workbooks.Open(FileName:=myPath & myFile)
DoEvents
Call cleanDataAndTransfer
wb.Close SaveChanges:=True
DoEvents
myFile = Dir
Loop
ResetSettings:
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
I would really appreciate any suggestions on how to solve this bug and any other improvements! Thanks in advance :)
I don't have a Mac to test this but you could try an InputBox.
update - no filter on Dir
Sub loopAllExcelFilesInFolder()
Sub loopAllExcelFilesInFolder2()
Const EXT = "csv"
Dim wb As Workbook, myPath As String, myFile As String
Dim count As Integer, isWindows As Boolean
myPath = ThisWorkbook.Path & Application.PathSeparator
myPath = VBA.InputBox("Enter folder", "Folder", myPath)
If myPath = "" Then Exit Sub
If Right(myPath, 1) <> Application.PathSeparator Then
myPath = myPath & Application.PathSeparator
End If
myFile = Dir(myPath)
Do While myFile <> ""
If Right(myFile, Len(EXT)) = EXT Then
Set wb = Workbooks.Open(Filename:=myPath & myFile)
Call cleanDataAndTransfer
wb.Close SaveChanges:=True
count = count + 1
End If
myFile = Dir
Loop
MsgBox count & " files cleaned", vbInformation
End Sub

How do I copy a csv Sheet into an excel file without changes

I've got am csv file which looks as follows
When I select all cells and copy/paste it manually into another excel file the result is the same as the original. Howevever, trying to do the same in VBA gives me the following result.
This is the code I am using.
Sub test()
Dim arr1 As Object
Set arr1 = CreateObject("System.Collections.ArrayList")
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select"
.AllowMultiSelect = False
.InitialFileName = strPath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
'-----------------------------------------------------------
Dim FileName As Variant
FileName = Dir(GetFolder & "\")
'-----------------------------------------------------------
While FileName <> ""
arr1.Add GetFolder & "\" & FileName
FileName = Dir
Wend
'-----------------------------------------------------------
Set fldr = Nothing
Dim i As Long
For i = 0 To arr1.Count - 1
'-------------------------------------------------------------------
Dim wkbk As Workbook
Set wkbk = Workbooks.Open(arr1(i))
wb1 = wkbk.Name
Set sht = wkbk.Worksheets(wkbk.Sheets(1).Name)
wkbk.Sheets(sht.Name).Copy After:=ThisWorkbook.Sheets("START")
ActiveSheet.Name = "NEW"
' MsgBox wkbk.Name
' ThisWorkbook.Sheets.Add.Name = "NEW"
' wkbk.Sheets(sht.Name).Cells.Copy
' ThisWorkbook.Sheets("NEW").Cells.Paste
wkbk.Close False
Next i
End Sub
Is there a way to get the same result as doing it manually?
Import CSV Files
Option Explicit
Sub importCSV()
Const InitialFolderPath As String = "F:\Test\2021"
Const FilePattern As String = "*.csv"
Dim dwb As Workbook: Set dwb = ThisWorkbook
Dim FolderPath As String
If Right(InitialFolderPath, 1) = "\" Then
FolderPath = InitialFolderPath
Else
FolderPath = InitialFolderPath & "\"
End If
Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
With fd
.Title = "Select"
.AllowMultiSelect = False
.InitialFileName = FolderPath
If .Show = False Then
MsgBox "You canceled."
Exit Sub
End If
FolderPath = .SelectedItems(1) & "\"
End With
Dim arl As Object: Set arl = CreateObject("System.Collections.ArrayList")
Dim FileName As String: FileName = Dir(FolderPath & FilePattern)
Do While FileName <> ""
arl.Add FolderPath & FileName
FileName = Dir
Loop
Application.ScreenUpdating = False
Dim swb As Workbook
Dim sws As Worksheet
Dim dws As Worksheet
Dim shId As Long
Dim i As Long
For i = 0 To arl.Count - 1
Set swb = Workbooks.Open(FileName:=arl(i), Local:=True)
Set sws = swb.Worksheets(1)
sws.Copy After:=dwb.Sheets(dwb.Sheets.Count)
Set dws = ActiveSheet
shId = shId + 1
On Error GoTo NewSheetError
dws.Name = "New" & shId
On Error GoTo 0
swb.Close False
Next i
'dwb.Save
Application.ScreenUpdating = True
Exit Sub
NewSheetError:
shId = shId + 1
Resume
End Sub

Issue calling a function for a user selected folder

I have a function that prompts the user to select a folder and a subroutine that will consolidate the files in the folder to a single document, but I cannot get the two to work together.
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
Sub ConslidateWorkbooksPrompt()
Dim FolderPath As String
Dim Filename As String
Dim Sheet As Worksheet
Application.ScreenUpdating = False
FolderPath = GetFolder()
Filename = Dir(FolderPath & "*.csv")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
For Each Sheet In ActiveWorkbook.Sheets
Sheet.Copy After:=ThisWorkbook.Sheets(1)
Next Sheet
Workbooks(Filename).Close
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
When I save the subroutine separately and run it where FolderPath = "C:\docs\SampleFolder\" then it runs fine. Instead of having to manually change the folder path, I'd like the user to be able to select their own, but I imagine I am somehow calling the function wrong.

Run Time Error 1004: Method 'Save As' Fail_of object' Workbook' Failed

The following VBA code results in a "SaveAs" error. I have not been able to figure it out. Just trying to change xlsb files into xls files. I have read most of the suggestions in the snawer query but none of the seem to work.
Option Explicit
Public Sub SaveAsXLS()
Dim wb As Workbook
Dim sh As Worksheet
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim nameWB As String
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
NextCode:
myPath = myPath
If myPath = "" Then Exit Sub
'Target File Extension (must include wildcard "*")
myExtension = "*.xlsb*"
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
Set wb = Workbooks.Open(Filename:=myPath & myFile)
Call DetermineNonBuiltinCommandBars
nameWB = Replace(myFile, ".xlsb", "")
ActiveWorkbook.SaveAs Filename:=nameWB, FileFormat:=xls <---- ERROR
ActiveWorkbook.Close savechanges:=False
myFile = Dir
Loop
End Sub

Resources