Loop Through Directory VBA to Copy Data With Format - vba

I have few files in a directory or a folder and I want to copy a range (values with format to the current sheet). I have VBA code and I think it is not in order or something is missing in the code. Please help me to fix the issue.
(I have defined named range in each files in the directory. Is it is possible to copy using the named range?)
Copy from directory files given path & from sheet2 & paste it to file "workbook.xlsm" Sheet "sheet1"
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\test"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = "workbook.xlsm" Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Sheets("Sheet2").Select
Range("A1:N24").Copy
Workbooks.Open ("Filepath & workbook.xlsm")
If Sheets("Sheet1").Range("A1") = vbNullString Then
Sheets("Sheet1").Range ("A1:N24")
Selection.PasteSpecial Paste:=xlPasteFormats
Selection.PasteSpecial Paste:=xlPasteValues
Else
Selection.Copy Sheets("sheet1").Cells(A1, Columns.Count).End(xlToLeft).Offset(0, 1)
End If
MyFile = Dir
Loop
End Sub

One question remains:
(I have defined named range in each files in the directory. Is it is possible to copy using the named range?)
It's certainly possible. Thus assuming the Defined Name range is "DATA".
Just replace this line:
sourceWbk.Sheets("Sheet2").Range("A1:N24").Copy
with this:
sourceWbk.Sheets("Sheet2").Range("DATA").Copy
Actually, OP mentioned that this Names are generated by another procedure with the address "A1:N24". So in the case that the address is changed then there will be a need to update every other procedure that refers to it, instead by using the Defined Name don't have to worry about it as it will be taking care by design. That why it’s a good practice to use Defined Names.

I'd use this method:
Sub LoopThroughDirectory()
Dim MyFile As String
Dim FilePath As String
Dim colFiles As Collection
Dim vFile As Variant
Dim wrkbkSource As Workbook
Dim wrkbkTarget As Workbook
Dim rngTarget As Range
FilePath = "C:\test\"
MyFile = "workbook.xlsm"
Set colFiles = New Collection
EnumerateFiles FilePath, "*.xlsm", colFiles
Set wrkbkTarget = Workbooks.Open(FilePath & MyFile)
For Each vFile In colFiles
If vFile <> FilePath & MyFile Then
Set wrkbkSource = Workbooks.Open(vFile, False)
wrkbkSource.Worksheets(1).Range("A1:N24").Copy
Set rngTarget = wrkbkTarget.Worksheets("Sheet1").Cells(1, wrkbkTarget.Worksheets("Sheet1").Columns.Count).End(xlToLeft)
rngTarget.PasteSpecial xlPasteFormats
rngTarget.PasteSpecial xlPasteValues
wrkbkSource.Close False
End If
Next vFile
End Sub
This procedure is needed to get all the files in the folder:
Sub EnumerateFiles(ByVal sDirectory As String, _
ByVal sFileSpec As String, _
ByRef cCollection As Collection)
Dim sTemp As String
sTemp = Dir$(sDirectory & sFileSpec)
Do While Len(sTemp) > 0
cCollection.Add sDirectory & sTemp
sTemp = Dir$
Loop
End Sub

Okay see if it works for you, had to add quite a bit
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Dim targetWbk As Workbook
Dim sourceWbk As Workbook
Filepath = "C:\test"
MyFile = Dir(Filepath)
Workbooks.Open (Filepath & "\workbook.xlsm")
Set sourceWbk = ActiveWorkbook
Do While Len(MyFile) > 0
If Not MyFile = "workbook.xlsm" And MyFile = "*.xls*" Then
Workbooks.Open (Filepath & MyFile)
Set sourceWbk = ActiveWorkbook
sourceWbk.Sheets("Sheet2").Range("A1:N24").Copy
If targetWbk.Sheets("Sheet1").Range("A1") = vbNullString Then
targetWbk.Sheets("Sheet1").Range("A1:N24").PasteSpecial xlPasteFormulas, xlPasteValues
Else
targetWbk.Sheets("sheet1").Cells(A1, Columns.Count).End(xlToLeft).Offset(0, 1).PasteSpecial xlPasteFormulas, xlPasteValues
End If
MyFile = Dir
End If
Loop
End Sub

Related

Copying a range from a hidden sheet

i have a vba code to copy and paste a range of data from multiple excel files in a folder. The sheet that has the data is hidden though. i need to modify my code to copy the hidden sheets range.
Sub Import_to_Master()
Dim sFolder As String
Dim sFile As String
Dim wbD As Workbook, wbS As Workbook
Application.ScreenUpdating = False Set wbS = ThisWorkbook sFolder =
wbS.Path & "\"
sFile = Dir(sFolder) Do While sFile <> ""
If sFile <> wbS.Name Then Set wbD = Workbooks.Open(sFolder & sFile)
'open the file; add condition to
' >>>>>> Adapt this part wbD.Sheets("data").Range("A3:BD3").Copy
wbS.Activate Sheets("data scorecards").Range("A" &
Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
Application.CutCopyMode = False ' >>>>>> wbD.Close savechanges:=True
'close without saving End If
sFile = Dir 'next file Loop Application.ScreenUpdating = True
End Sub
This looks appropriate. I've used direct value transfer instead of copy, paste special, values.
Option Explicit
Sub Import_to_Master()
Dim sFolder As String, sFile As String
Dim wbS As Workbook
Application.ScreenUpdating = False
Set wbS = ThisWorkbook
sFolder = wbS.Path & "\"
sFile = Dir(sFolder & "*.xl*")
Do While sFile <> ""
If sFile <> wbS.Name Then
'open the file; add condition to
With Workbooks.Open(sFolder & sFile)
' >>>>>> Adapt this part wbD
With .Worksheets("data").Range("A3:BD3")
wbS.Worksheets("data scorecards").Cells(Rows.Count, "A").End(xlUp).Offset(1, 0).Resize(.Rows.Count, .Columns.Count) = .Value
End With
'close without saving
.Close savechanges:=False
End With
End If
sFile = Dir 'next file
Loop
Application.ScreenUpdating = True
End Sub

Open workbooks in filepath and copy sheet 2 to Masterworkbook

I would like to open all workbooks in a filepath on my hard-drive and then copy table data from sheet 2 to Master workbook with the name of Master.
I found this code and have modified it to suit my needs but I'm stuck.
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow
Dim Filepath As String
Filepath = "C:\home\Se\058 \dxakmh\Desktop\TestMiljö\Prognosverktyg\Sektionsfil\Gruppfiler"
MyFile = Dir(Filepath)
Do While Len(MyFile) > 0
If MyFile = “master.xlsm” Then
Exit Sub
End If
Workbooks.Open (Filepath & MyFile)
Worksheets("FärdigÖnskemål").Range("A4:D4").Select
ActiveWorkbook.Close
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
ActiveSheet.Paste Destination:=Worksheets("DataÖnskemål").Range(Cells(erow, 1), Cells(erow, 4))
MyFile = Dir
Loop
End Sub
Any help this friday?
According to your code, it's not clear what Worksheet is the destination sheet (the one you want to paste to), is it Sheet1 or Worksheets("DataÖnskemål").
Anyway, in my code it pastes to Sheet1, let me know if you meant something else.
Code
Option Explicit
Sub LoopThroughDirectory()
Dim MyFile As String
Dim erow As Long
Dim Filepath As String
Dim wb As Workbook
Filepath = "C:\home\Se\058 \dxakmh\Desktop\TestMilj?\Prognosverktyg\Sektionsfil\Gruppfiler\"
MyFile = Dir(Filepath)
Do While MyFile <> ""
If Not MyFile Like "master.xlsm" Then
Set wb = Workbooks.Open(Filepath & MyFile)
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
wb.Worksheets("DataÖnskemål").Range("A4:D4").Copy Destination:=Sheet1.Range("A" & erow)
wb.Close False
End If
MyFile = Dir()
Loop
End Sub
I would recommend using FileSystemObject instead:
Sub LoopThroughDirectory()
Dim MyFile As File
Dim erow As Long
Dim Filepath As String
Dim wb As Workbook
Dim FSO As New Scripting.FileSystemObject
Filepath = "C:\home\Se\058 \dxakmh\Desktop\TestMilj?\Prognosverktyg\Sektionsfil\Gruppfiler"
For Each MyFile In FSO.GetFolder(Filepath).Files
If Not MyFile.Name Like "master.xlsm" Then
Debug.Print MyFile.Path
Set wb = Workbooks.Open(MyFile.Path)
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
wb.Worksheets("DataÖnskemal").Range("A4:D4").Copy Destination:=Sheet1.Range("A" & erow)
wb.Close False
End If
Next
End Sub
You have to add Microsoft Scripting Runtime reference to your project.
You can read more here

Combining macros in Excel

I'm trying to combine/nest 3 different functions in Excel VBE: open, loop, and click. I have them written out separately, but am unsure of how to combine them. I've tried the "call macro" function but got a compile error returned to me.
The goal is to open a bunch of files within a certain folder and click on the URL in all of them (the URL will not always be the same, so I need a click function that targets any unknown URL within a sheet).
Open macro:
Sub openMyfile()
Dim Source As String
Dim StrFile As String
Source = "/users/kmogilevsky/Desktop/IC_new/"
StrFile = Dir("/users/kmogilevsky/Desktop/IC_new/")
Do While Len(StrFile) > 0
Workbooks.Open Filename:=Source & StrFile
StrFile = Dir("/users/kmogilevsky/Desktop/IC_new/")
Loop
End Sub
Loop macro:
Sub LoopThroughFiles()
Dim MyObj As Object, MySource As Object, file As Variant
Set MySource = MyObj.GetFolder("/users/kmogilevsky/Desktop/IC_new/")
For Each file In MySource.Files
If InStr(file.Name, "test") > 0 Then
End If
Next file
End Sub
Click macro (this needs some work):
Private Sub CommandButton1_Click()
Call NewSub
End Sub
Sub ReadWorkbooksInCurrentFolder()
Dim wbDst As Workbook
Dim wbSrc As Workbook
Dim MyPath As String
Dim strFilename As String
'Stop annoying popups while macro is running
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
'When working with many open workbooks its good to explicitly reference all workbooks, makes sure your code works and easier to read, understand and remember which workbook is which.
Set wbDst = ThisWorkbook
srcSheetName = "Data"
dstSheetName = "Results"
'I want to loop through all .xlsx files in the folder
MyPath = ThisWorkbook.Path
strFilename = Dir(MyPath & "\*.xlsx", vbNormal)
If Len(strFilename) = 0 Then
MsgBox "No workbooks found ending in .xlsx in current folder"
Exit Sub
End If
Do Until strFilename = ""
Set wbSrc = Workbooks.Open(Filename:=MyPath & "\" & strFilename)
Call CollectData(wbDst, wbSrc, dstSheetName, srcSheetName)
wbSrc.Close
strFilename = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
Sub CollectData(ByRef wbDst as Workbook, ByRef wbSrc as Workbook, dstSheetName as String, srcSheetName as String)
'Copy cell A1 contents in source workbook to destination workbook cell A1
wbDst.Sheets(dstSheetName).Range("A1") = wbSrc.Sheets(srcSheetName).Range("A1")
End Sub
Please edit the subroutine CollectData() so that it suits your needs, i.e. performs the click / url open. (I am not familiar with opening urls from excel, but I loop through workbooks often)
This code will open all Excel files in the IC_New folder on the desktop.
It will then look at each sheet and follow any hyperlinks that are on the sheet.
Sub Open_ClickHyperlinks()
Dim sPath As String
Dim vFiles As Variant
Dim vFile As Variant
Dim wrkBk As Workbook
Dim wrkSht As Worksheet
Dim HLink As Hyperlink
sPath = CreateObject("WScript.Shell").SpecialFolders("Desktop") & Application.PathSeparator & _
"IC_New" & Application.PathSeparator
'Return all files that have an extension starting with xls.
vFiles = EnumerateFiles(sPath, "xls*")
'Loop through each file.
For Each vFile In vFiles
'Open the file
Set wrkBk = Workbooks.Open(Filename:=vFile, UpdateLinks:=False)
With wrkBk
'Loop through each worksheet in the file.
For Each wrkSht In .Worksheets
'Loop through each hyperlink on the worksheet.
For Each HLink In wrkSht.Hyperlinks
HLink.Follow
Next HLink
Next wrkSht
.Close SaveChanges:=False
End With
Next vFile
End Sub
'Get all files in the specified folder, default to include all subfolders as well.
Public Function EnumerateFiles(sDirectory As String, _
Optional sFileSpec As String = "*", _
Optional InclSubFolders As Boolean = True) As Variant
EnumerateFiles = Filter(Split(CreateObject("WScript.Shell").Exec _
("CMD /C DIR """ & sDirectory & "*." & sFileSpec & """ " & _
IIf(InclSubFolders, "/S ", "") & "/B /A:-D").StdOut.ReadAll, vbCrLf), ".")
End Function

PasteSpecial Method of Range Run Error

Sub LoopOtherRevenue()
Dim MyFile As String
Dim FilePath As String
FilePath = "C:\Users\jdubbaneh002\Desktop\Racetrac Other\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
If MyFile = "Book1.xlsm" Then
Exit Sub
End If
ActiveSheet.Range("A1:B14").Copy
Workbooks.Open (FilePath & MyFile)
ActiveWorkbook.Worksheets("A2) Monthly P&L (Source)").Activate
Range("B746:C759").PasteSpecial xlPasteValues
Application.CutCopyMode = False
ActiveWorkbook.Close
MyFile = Dir
Loop
End Sub
Get a paste special error on line Range("B746:C759").PasteSpecial xlPasteValues
The values are being pasted into a combo box. that is where the error is coming from.
For me it seems like the file path is missing a "\"
FilePath = "C:\Users\jdubbaneh002\Desktop\Racetrac Other"
...
MyFile = Dir(FilePath)
...
If MyFile = "Book1.xlsm" Then
...
Workbooks.Open (FilePath & MyFile)
Correct:
Workbooks.Open (FilePath & "\" & MyFile)
Did you try debugging? Where does it throw the error?
I can see all sorts of issues because you're using ActiveWorkbook after opening the 2nd workbook. Is ActiveWorkbook still pointing at the one where the code is, or is it actually pointing at the one you just opened?
Create & set an as Workbook variable as assign the one the code is in to one, and the workbook you're opening to the other. That will eliminate all confusion.
Try this:
Sub LoopOtherRevenue()
Dim rgCopy as Range
Dim MyFile As String
Dim FilePath As String
Dim wb as Workbook
FilePath = "destination folder\"
MyFile = Dir(FilePath)
Set rgCopy = ActiveSheet.Range("A1:B14")
Do While Len(MyFile) > 0
If MyFile = "Book1.xlsm" Then
Exit Sub
End If
set wb Workbooks.Open(FilePath & "\" & MyFile)
rgCopy.Copy Destination:=wb.Worksheets("A2) Monthly P&L (Source)").Range("B746")
wb.Close
MyFile = Dir
Loop
End Sub

Writing a formula in VBA while looping through various files?

I have the following code with a specific file name:
BD.Sheets("Sheet1").Cells(Rows.Count, 6).End(xlUp).Offset(1, 0).Formula = "=SUMIF('P:\Actuary\Cash Flow Forecast\Annual and Quarterly Budget Data\[ECMQA 2012Q1.xls]Sheet1'!$D$13:$D$234,D2,OFFSET('P:\Actuary\Cash Flow Forecast\Annual and Quarterly Budget Data\[ECMQA 2012Q1.xls]Sheet1'!$D$13:$D$234,0,MATCH(E2,'P:\Actuary\Cash Flow Forecast\Annual and Quarterly Budget Data\[ECMQA 2012Q1.xls]Sheet1'!$D$12:$R$12,0)-1))"
However, I'm running a loop which goes into a folder and selects all the files within it (the file above is in that folder, I was testing my code out to see if it worked for one file):
Dim wb As Workbook, sFile As String, sPath As String
Dim itm As Variant
Dim strFileNames As String
sPath = "C:\Actuary\Cash Flow Forecast\Annual and Quarterly Budget Data\"
''Retrieve the current files in directory
sFile = Dir(sPath)
Do While sFile <> ""
strFileNames = strFileNames & "," & sFile
sFile = Dir()
Loop
''Open each file found
For Each itm In Split(strFileNames, ",")
If itm <> "" Then
Set wb = Workbooks.Open(sPath & itm)
''LOTS OF CALCULATIONS, INCLUDING ABOVE CODE
End If
Next itm
How would I write the first code if I don't know the file name (since it's looping through all of them)?
Any help will be appreciated!!
Sub WriteFormulas()
Dim sFile As String
Dim sPath As String
Dim sh As Worksheet
Dim rNext As Range
sPath = Environ("USERPROFILE") & "\My Documents\Tester\"
'Get the first file
sFile = Dir(sPath & "*.xls")
Do While Len(sFile) > 0
'don't process this workbook
If sFile <> ThisWorkbook.Name Then
'set a variable to the first sheet in the file
Set sh = Workbooks.Open(sFile).Worksheets(1)
'find the next available cell in column A in this workbook
Set rNext = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Offset(1, 0)
'create a formula using the address with the external argument
rNext.Formula = "=SUM(" & sh.Range("A1:A10").Address(True, True, xlA1, True) & ")"
'close the workbook
sh.Parent.Close False
End If
sFile = Dir
Loop
End Sub
When you close the workbook, Excel will expand the references to the full path and file name. So while Range("A1").Address(,,,true) might resolve to
[MyBook.xls]Sheet1!A1
when you close MyBook.xls, it will convert to
'C:\Path\[MyBook.xls]Sheet1'!A1