How to use file path from a cell in VBA? - vba

I'm running a VBA script in order to count number of rows in each file in a selected folder and then to display it in an active Workbook.
Option Explicit
Sub CountRows()
Dim wbSource As Workbook, wbDest As Workbook
Dim wsSource As Worksheet, wsDest As Worksheet
Dim strFolder As String, strFile As String
Dim lngNextRow As Long, lngRowCount As Long
Application.ScreenUpdating = False
Set wbDest = ActiveWorkbook
Set wsDest = wbDest.ActiveSheet
strFolder = Dir(Range("C7").Value)
strFile = Dir(strFolder & "*.xlsx")
lngNextRow = 11
Do While Len(strFile) > 0
Set wbSource = Workbooks.Open(Filename:=strFolder & strFile)
Set wsSource = wbSource.Worksheets(1)
lngRowCount = wsSource.UsedRange.Rows.Count
wsDest.Cells(lngNextRow, "F").Value = lngRowCount
wbSource.Close savechanges:=False
lngNextRow = lngNextRow + 1
strFile = Dir
Loop
Application.ScreenUpdating = True
End Sub
Chooing a folder, I would like to use the directory that is inserted in an active WorkBook cell "C7" instead of writing a directory in a script.
I tried to substitute:
strFolder = "C:\Users\user\Desktop\"
with
strFolder = Dir(Range("C7").Value)
but it does not work. Maybe someone has any ideas? Thanks!

This line strFolder = Dir(Range("C7").Value) finds firts file in directory (from C7) and then writes path of this file into variable strFolder (say, C:\temp\somefile.txt).
Next line of your code: strFile = Dir(strFolder & "*.xlsx") takes this path and adds *.xlsx. In result you would get strFile = Dir("C:\temp\somefile.txt*.xlsx") and that's wrong.
So, change this code:
strFolder = Dir(Range("C7").Value)
strFile = Dir(strFolder & "*.xlsx")
to next one:
strFolder = Range("C7").Value
strFile = Dir(strFolder & "*.xlsx")
Btw, I'd recommend you to specify sheet for Range("C7") like this: wsDest.Range("C7")

Try this
dim strPath as string
strPath = CurDir + "NameofFile.xls"

Related

Preventing workbooks from being stored in VBA Project Explorer

The code I have loops through a folder that has 100+ files (with more files being added daily) and copies files, data, etc. Every file that I loop through ends up in the VBA Project Explorer as you can see from the picture. This is really slowing down the run time of my code. Is there any way I can prevent each workbook from being added to the Project Explorer? Also, I haven't run my code with the optimize subroutines that I call to because I added those after running my original code (and now the editor is basically frozen). I attached my code as well as the picture of my issue below!
Sub TransferSAPCLData_Click()
'Code Optimization
Call OptimizeCode_Begin
'Declaring and Setting Variables
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim MyDir As String
Dim fil As Scripting.file
Dim FolderSource As Scripting.Folder
Dim FolderPathDest As String, wbDest As Workbook, wsDest As Worksheet
Dim wbSource As Workbook, wsSource As Worksheet
Dim lrDest As Long, fileDest As String, lrSource As Long
Dim CurrentFile As String
Dim fileSource As String
MyDir = "C:\Users\quirk\Desktop\Cory Project\Wave 1A Content\SAPCL Spreadsheets\SAPCL Raw Data Files"
'Defining destination characteristics
FolderPathDest = "C:\Users\quirk\Desktop\Cory Project\Wave 1A Content\Master SAPCL Folder"
fileDest = "C:\Users\quirk\Desktop\Cory Project\Wave 1A Content\Master SAPCL Folder\Function Master File.xlsm"
'Workbooks.Open Filename:=fileDest
Set wbDest = ActiveWorkbook ' Workbooks("MASTER.xlsx")
Set wsDest = wbDest.Worksheets("Sheet1")
'Looping through files
Set FolderSource = fso.GetFolder(MyDir)
For Each fil In FolderSource.Files
Debug.Print fil.Name
CurrentFile = fil.Name
If Not fso.FileExists(FolderPathDest & "\" & fil.Name) Then
fso.CopyFile _
Source:=MyDir & "\" & fil.Name _
, Destination:=FolderPathDest & "\" & fil.Name
fileSource = MyDir & "\" & fil.Name
Workbooks.Open Filename:=fileSource '
ActiveWindow.Visible = False
Set wbSource = Workbooks(CurrentFile)
Set wsSource = wbSource.Worksheets(1)
lrSource = wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row
lrDest = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).Row + 1
wsSource.Range("A2:V" & lrSource).Copy Destination:=wsDest.Range("A" & lrDest)
End If
Next fil
'Optimize Code
Call OptimizeCode_End
End Sub

Copy/Paste function within ForEach loop doesn't do anything VBA

Previously I was having issues with the lrSource variable not referencing the correct worksheet, but I added code to fix this issue. Before I corrected the issue, the code would paste some data into "MASTER.xlsx" but not the correct portions due to the lrSource variable not getting the correct last row. Now, I can get the correct last row and I don't receive any errors, but no data is copied to the file destination ("MASTER.xlsx")...Any suggestions?
Sub btnUpdateSAPData_Click()
'Declaring and Setting Variables
Dim fso As Scripting.FileSystemObject
Set fso = New Scripting.FileSystemObject
Dim MyDir As String
Dim fil As Scripting.file
Dim FolderSource As Scripting.Folder
Dim FolderPathDest As String, wbDest As Workbook, wsDest As Worksheet
Dim wbSource As Workbook, wsSource As Worksheet
Dim lrDest As Long, fileDest As String, lrSource As Long
Dim CurrentFile As String
Dim fileSource As String
MyDir = "C:\Users\quirk\Desktop\Cory Project\Wave 1A Content\SAPCL Spreadsheets\July 2018"
'Defining destination characteristics
FolderPathDest = "C:\Users\quirk\Desktop\Cory Project\VBA Code\Master FOlder"
fileDest = "C:\Users\quirk\Desktop\Cory Project\VBA Code\Master FOlder\MASTER.xlsx"
'Workbooks.Open Filename:=fileDest
Set wbDest = ActiveWorkbook ' Workbooks("MASTER.xlsx")
Set wsDest = wbDest.Worksheets("Sheet1")
'Looping through files
Set FolderSource = fso.GetFolder(MyDir)
For Each fil In FolderSource.Files
Debug.Print fil.Name
CurrentFile = fil.Name
If Not fso.FileExists(FolderPathDest & "\" & fil.Name) Then
fso.CopyFile _
Source:=MyDir & "\" & fil.Name _
, Destination:=FolderPathDest & "\" & fil.Name
fileSource = MyDir & "\" & fil.Name
Workbooks.Open Filename:=fileSource '
ActiveWindow.Visible = False
Set wbSource = Workbooks(CurrentFile)
Set wsSource = wbSource.Worksheets(1)
lrSource = wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row
lrDest = wsDest.Range("A" & wsDest.Rows.Count).End(xlUp).Row + 1
Range("A2:V" & lrSource).Copy Destination:=wsDest.Range("A" & lrDest)
End If
Next fil
End Sub

VBA copies content from each file in the folder to the corresponding worksheet in the master workbook

I need some help on the following code, basically i have about 50 excel files in a folder and i want to copy data from each excel file to the master file. There are 3 worksheets in each file with the name 6D6 Cash, 6D6 Position and 6D6 Transactions and masterworkbook also has those tabs so for example macro will copy all the data from 6D6 cash worksheet in each excel file to the 6D6 cash worksheet in the master workbook and the new data will go below the last filled row. Also the row in each excel file has the header so that won't go in obviously.
For some reason, it's not working, as in the code is not working at all. What could be the reason?
Sub Adam1()
Dim wbDst As Workbook
Dim wsDst As Worksheet
Dim wbSrc As Workbook
Dim wsSrc As Worksheet
Dim MyPath As String
Dim strFilename As String
Dim lLastRow As Long
Application.DisplayAlerts = False
Application.EnableEvents = False
Application.ScreenUpdating = False
Set wbDst = ThisWorkbook
MyPath = "C:\Users\Adam\Desktop\6D6 files"
strFilename = Dir(MyPath & "*.xls*", vbNormal)
Do While strFilename <> ""
Set wbSrc = Workbooks.Open(MyPath & strFilename)
'loop through each worksheet in the source file
For Each wsSrc In wbSrc.Worksheets
'Find the corresponding worksheet in the destination with the same name as the source
On Error Resume Next
Set wsDst = wbDst.Worksheets(wsSrc.Name)
On Error GoTo 0
If wsDst.Name = wsSrc.Name Then
lLastRow = wsDst.UsedRange.Rows(wsDst.UsedRange.Rows.Count).Row + 1
wsSrc.UsedRange.Copy
wsDst.Range("A" & lLastRow).PasteSpecial xlPasteValues
End If
Next wsSrc
wbSrc.Close False
strFilename = Dir()
Loop
Application.DisplayAlerts = True
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
I think you have an incomplete string.
MyPath = "C:\Users\Adam\Desktop\6D6 files"
strFilename = Dir(MyPath & "*.xls*", vbNormal)
Will be returning C:\Users\Adam\Desktop\6D6 filessomefile.xls
MyPath = "C:\Users\Adam\Desktop\6D6 files\" 'with the extra slash
strFilename = Dir(MyPath & "*.xls*", vbNormal)

A way to alter GetFormData code to search subfolders

I have been using the getformdata code (below) to collate data from VBA Word Forms, but I would love to know if it's possible to alter the code so I can select a higher folder and it will search all subfolders.
Sub GetFormData()
'Note: this code requires a reference to the Word object model
Application.ScreenUpdating = False
Dim wdApp As New Word.Application
Dim wdDoc As Word.Document
Dim FmFld As Word.FormField
Dim strFolder As String, strFile As String
Dim WkSht As Worksheet, i As Long, j As Long
strFolder = GetFolder
If strFolder = "" Then Exit Sub
Set WkSht = ActiveSheet
i = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row
strFile = Dir(strFolder & "\*.doc", vbNormal)
While strFile <> ""
i = i + 1
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
j = 0
For Each FmFld In .FormFields
j = j + 1
WkSht.Cells(i, j) = FmFld.Result
Next
End With
wdDoc.Close SaveChanges:=False
strFile = Dir()
Wend
I have found code that looks at subfolders, but it seems to be a sub in itself and I don't know where in relation to this I could use it. Thanks.

Excel VBA: select one row down in a loop

I have a source folder that contains many xls files. I want to create a master file - collect all information into one database from all files in the given source.
The following code creates 2 columns in master file and enters 2 values from the given source file (one file):
Sub getData()
Dim XL As Excel.Application
Dim WBK As Excel.Workbook
Dim scrFile As String
Dim myPath As String
myPath = ThisWorkbook.path & "\db\" 'The source folder
scrFile = myPath & "1.xlsx" 'Select first file
' Sheet name in the master file is "Sh"
ThisWorkbook.Sheets("Sh").Range("A1").Value = "Column 1"
ThisWorkbook.Sheets("Sh").Range("B1").Value = "Column 2"
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
ThisWorkbook.Sheets("Sh").Range("A2").Value = WBK.ActiveSheet.Range("A10").Value
ThisWorkbook.Sheets("Sh").Range("B2").Value = WBK.ActiveSheet.Range("C5").Value
WBK.Close False
Set XL = Nothing
Application.ScreenUpdating = True
End Sub
Now I want to loop through all files and save the values from cells "A10" and "C5" from each file in one database, so the loop should select the next row to save new values.
I have an idea how to loop through all files, but don't know how to switch to the next row:
scrFile = Dir(myPath & "*.xlsx")
Do While scrFile <> ""
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
' Here should be the code to save the values of A10 and C5 of the given file
'in the loop in next available row of the master file.
WBK.Close False
Set XL = Nothing
scrFile = Dir
Loop
Any help will be highly appreciated! :)
For simplicity, just use a counter:
scrFile = Dir(myPath & "*.xlsx")
n = 1 ' skip the first row with headers
Do While scrFile <> ""
n = n + 1
Set XL = CreateObject("Excel.Application")
Set WBK = XL.Workbooks.Open(scrFile)
' save the values of A10 and C5 of the given file in the next row
ThisWorkbook.Sheets("Sh").Range("A" & n).Value = WBK.ActiveSheet.Range("A10").Value
ThisWorkbook.Sheets("Sh").Range("B" & n).Value = WBK.ActiveSheet.Range("C5").Value
WBK.Close False
Set XL = Nothing
scrFile = Dir
Loop
msgbox n & " files imported."
BTW, you don't need to start a second Excel instance (CreateObject("Excel.Application")) just to open a second workbook. This will slow down your code a lot. Just open, read and close it. Address your master workbook not by ThisWorkbook but assign a varible to it:
Dim masterWB As Excel.Workbook
set masterWB = ThisWorkbook
...
masterWB.Sheets("Sh").Range("A" & n).Value = WBK.ActiveSheet.Range("A10").Value
You need to recalculate last row in the loop wtih End() function.
Like this for range .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0)
Or to have an integer .Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Row
Give this a try :
Sub getData()
Application.ScreenUpdating = False
Dim XL As Excel.Application, _
WBK As Excel.Workbook, _
MS As Worksheet, _
scrFile As String, _
myPath As String
'Sheet name in the master file is "Sh"
Set MS = ThisWorkbook.Sheets("Sh")
'The source folder
myPath = ThisWorkbook.Path & "\db\"
MS.Range("A1").Value = "Column 1"
MS.Range("B1").Value = "Column 2"
Set XL = CreateObject("Excel.Application")
scrFile = Dir(myPath & "*.xlsx")
Do While scrFile <> ""
Set WBK = XL.Workbooks.Open(scrFile)
' Here should be the code to save the values of A10 and C5 of the given file
'in the loop in next available row of the master file.
With MS
.Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Value = WBK.ActiveSheet.Range("A10").Value
.Range("B" & .Rows.Count).End(xlUp).Offset(1, 0).Value = WBK.ActiveSheet.Range("C5").Value
End With
WBK.Close False
scrFile = Dir
Loop
XL.Quit
Set XL = Nothing
Set MS = Nothing
Set WBK = Nothing
Application.ScreenUpdating = True
End Sub
I actually have a code here that will loop through each file and deposit the code into your main file. You are also able to choose the directory of the target folder.
Sub GatherData()
Dim sFolder As String
Application.ScreenUpdating = True
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = Application.DefaultFilePath & "\"
.Title = "Please select a folder..."
.Show
If .SelectedItems.Count > 0 Then
sFolder = .SelectedItems(1) & "\"
Else
Exit Sub
End If
End With
Call Consolidate(sFolder, ThisWorkbook)
End Sub
Private Sub Consolidate(sFolder As String, wbMaster As Workbook)
Dim wbTarget As Workbook
Dim objFso As Object
Dim objFiles As Object
Dim objSubFolder As Object
Dim objSubFolders As Object
Dim objFile As Object
Dim ary(3) As Variant
Dim lRow As Long
'Set Error Handling
On Error GoTo EarlyExit
'Create objects to enumerate files and folders
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFiles = objFso.GetFolder(strFolder).Files
Set objSubFolders = objFso.GetFolder(strFolder).subFolders
'Loop through each file in the folder
For Each objFile In objFiles
If InStr(1, objFile.Path, ".xls") > 0 Then
Set wbTarget = Workbooks.Open(objFile.Path)
With wbTarget.Worksheets(1)
ary(0) = .Range("B8") 'here you can change the cells you need the data from
ary(1) = .Range("B12")
ary(2) = .Range("B14")
End With
With wbMaster.Worksheets(1)
lRow = .Range("E" & .Rows.Count).End(xlUp).Offset(1, 0).Row 'here you can change the row the data is deposited in
.Range("E" & lRow & ":G" & lRow) = ary
End With
wbTarget.Close savechanges:=False
End If
Next objFile
'Request count of files in subfolders
For Each objSubFolder In objSubFolders
Consolidate objSubFolder.Path, wbMaster
Next objSubFolder
EarlyExit:
'Clean up
On Error Resume Next
Set objFile = Nothing
Set objFiles = Nothing
Set objFso = Nothing
On Error GoTo 0
End Sub