Home » excel » excel – How to use file path from a cell in VBA?

excel – How to use file path from a cell in VBA?

Posted by: admin April 23, 2020 Leave a comment


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

    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!

How to&Answers:

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"