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\"
strFolder = Dir(Range("C7").Value)
but it does not work. Maybe someone has any ideas? Thanks!
strFolder = Dir(Range("C7").Value) finds firts file in directory (from
C7) and then writes path of this file into variable
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:
dim strPath as string strPath = CurDir + "NameofFile.xls"