我正在尝试使用For循环定义文件路径和文件名。
执行主要操作(在此示例中为行数)后,我需要同时路径到下一个文件路径和下一个文件名,然后执行主操作(行数)。
但是我在使用Next时遇到了一些问题,因为我尝试使用的顺序是错误的。也许有人可以帮忙吗?提前谢谢!
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
Dim LastRow
Dim cl As Range
Dim cell As Range
LastRow = wsDest.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
lngNextRow = wsDest.Range("F" & wsDest.Rows.Count).End(xlUp).Row + 1
'Here I define a Path to the file
For Each cl In wsDest.Range("G11:G" & LastRow)
strFolder = cl.Value
'Here I define File name
For Each cell In wsDest.Range("C11:C" & LastRow)
strFile = cell.Value
'Here happens count of row or any other action
Set wbSource = Workbooks.Open(Filename:=strFolder & strFile)
Set wsSource = wbSource.Worksheets(1)
lngRowCount = wsSource.UsedRange.Rows.Count
wsDest.Cells(lngNextRow, "F").Value = lngRowCount - 1
wbSource.Close savechanges:=False
lngNextRow = lngNextRow + 1
'Then i need to pass to the next Path & The next file name
Next cell
Next cl
End Sub
答案 0 :(得分:0)
用这个代替你的2循环结构:
For Each cl In wsDest.Range("G11:G" & LastRow)
strFolder = cl.Value
strFile = wsDest.Range("G" & cl.Row).Value
Set wbSource = Workbooks.Open(Filename:=strFolder & strFile)
Set wsSource = wbSource.Worksheets(1)
lngRowCount = wsSource.UsedRange.Rows.Count
wsDest.Cells(lngNextRow, "F").Value = lngRowCount - 1
wbSource.Close savechanges:=False
lngNextRow = lngNextRow + 1
Next cl
它将在每行上打开文件,文件夹在同一行
答案 1 :(得分:0)
在结果中我使用它来按行列出文件:
For Each cl In wsDest.Range("G11:G" & LastRow)
strFolder = cl.Value
iCol = 3
strFile = Cells(lngNextRow, iCol).Value
Set wbSource = Workbooks.Open(Filename:=strFolder & strFile)
Set wsSource = wbSource.Worksheets(1)
lngRowCount = wsSource.UsedRange.Rows.Count
wsDest.Cells(lngNextRow, "F").Value = lngRowCount - 1
wbSource.Close savechanges:=False
lngNextRow = lngNextRow + 1
Next