如何在VBA中使用来自单元格的文件路径?

时间:2014-02-19 10:26:55

标签: excel vba excel-vba path cell

我正在运行VBA脚本,以便计算所选文件夹中每个文件的行数,然后将其显示在活动的工作簿中。

 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一个文件夹,我想使用插入活动WorkBook单元格“C7”中的目录,而不是在脚本中编写目录。 我试图替换:

strFolder = "C:\Users\user\Desktop\"

 strFolder = Dir(Range("C7").Value)

但它不起作用。也许有人有任何想法?谢谢!

2 个答案:

答案 0 :(得分:1)

此行strFolder = Dir(Range("C7").Value)在目录中找到firts文件(来自C7),然后将此文件的路径写入变量strFolder(例如{{1} }})。

代码的下一行:C:\temp\somefile.txt采用此路径并添加strFile = Dir(strFolder & "*.xlsx")。结果你会得到*.xlsx,这是错误的。

所以,更改此代码:

strFile = Dir("C:\temp\somefile.txt*.xlsx")

到下一个:

strFolder = Dir(Range("C7").Value)
strFile = Dir(strFolder & "*.xlsx")

顺便说一句,我建议您指定strFolder = Range("C7").Value strFile = Dir(strFolder & "*.xlsx") 这样的表格:Range("C7")

答案 1 :(得分:1)

试试这个

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