最温暖的问候,目前我的Excel工作表中有一个模板。 我在做什么实际上是循环遍历多个文件夹,每个文件夹由多个文件组成,比较数据并获得结果。结果以这种方式出现Outcome结果是比较所有文件夹中的所有文件后的结果。
我看的是,当它循环到一个新文件夹时,结果将显示行偏移量为9.这意味着每个文件夹将显示一组结果。 Desired Outcome
这是我编写的循环遍历每个文件夹的代码:
Sub SearchReport()
Dim FileSystem As Object
Application.ScreenUpdating = False
Workbooks("List Folder Name.xlsm").Worksheets("Main Menu").Activate
counter = 2
Do While Range("A" & counter).Value <> "" 'do when Range A is not empty (folder path)
If Range("C" & counter).Value = "Yes" Then 'check Range C, do when Range C = Yes
HostFolder = Range("A" & counter).Value & "\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
Report FileSystem.getFolder(HostFolder) 'HostFolder is the folder path from Range A
counter = counter + 1
Else
counter = counter + 1
End If
Loop
Application.ScreenUpdating = True
End Sub
Sub Report(Folder)
Dim SubFolder
Dim subfld As Folder
Dim subfldr As Folder
Dim File As File
Dim MyPath As String
Dim Wksht As Worksheet
Dim wbk As Workbook
Dim N As Long
Application.ScreenUpdating = False
For Each SubFolder In Folder.SubFolders 'loop through subfolders in the first folder path
If SubFolder.Name = "Report" Then 'look for a folder named "Report"
MyPath = SubFolder.Path & "\"
fileName = Dir(MyPath & "*al.dat") 'look for files which is ended with "al.dat" in the "Report" folder
Do While Len(fileName) > 0 'open the files
Set wbk = Workbooks.Open(MyPath & fileName)
Set Wrksht = wbk.Worksheets(1)
find
wbk.Close True
fileName = Dir
Loop
Else
Sheets("Main Menu").Activate
Report SubFolder
End If
Next
End Sub
在数据处理过程中,我将结果设置为以这种方式插入:
With Workbooks("List Folder Name.xlsm").Sheets("Result")
.Range("D7").Value = H
.Range("A7").Value = HX
.Range("B7") = HY
.Range("C7") = HY2
End With
有没有办法达到我想要的结果?我希望我能得到一些帮助或建议,任何努力都表示赞赏!谢谢!
答案 0 :(得分:0)
您的此代码仅允许输出到第7行:
With Workbooks("List Folder Name.xlsm").Sheets("Result")
.Range("A7").Value = HX
.Range("B7") = HY
.Range("C7") = HY2
.Range("D7").Value = H
End With
在我看来,你需要用代码替换它,也许从第7行开始,然后每次将行偏移9。这是使用应用于.offset()
意味着偏移r.offset(x,y)
行和x
列的范围的y
函数来完成的。这只是代码的一个开始。我建议您逐步理解,然后根据需要进行修改:
dim r as range, sh as worksheet, i as integer, numberOfEntries as integer
set sh = Workbooks("List Folder Name.xlsm").Sheets("Result")
set r= sh.range("A6")
For i = 0 to numberOfEntries
With sh
r.offset(i*9,0) = "file name"
r.offset(i*9+1,0) = HX
r.offset(i*9,1) = "spur freq"
r.offset(i*9+1,1) = HY
r.offset(i*9,2) = "spur.."
r.offset(i*9+1,2) = HY2
r.offset(i*9,3) = "margin"
r.offset(i*9+1,3) = H
end with
next i