如何使用VBA中的单元格的文件path?

我正在运行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 

查找一个文件夹,我想使用插入到活动WorkBook单元格“C7”中的目录,而不是在脚本中编写目录。 我试图replace:

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

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

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

这行strFolder = Dir(Range("C7").Value)在目录(从C7 strFolder = Dir(Range("C7").Value)findfirts文件,然后把这个文件的path写入variablesstrFolder (比如C:\temp\somefile.txt )。

您的代码的下一行: strFile = Dir(strFolder & "*.xlsx")采用此path并添加*.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") 

顺便说一句,我build议你指定Range("C7")如下所示: wsDest.Range("C7")

尝试这个

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