[英]How can I write Excel VBA code to repeat until it reaches the worksheet edge?
[英]How do I, modify vba code to repeat until finished?
我发现了一段 vba 代码,它计算特定文件夹中 xml 文件的数量,我将其修改为仅计算具有特定字符串(位于单元格 F3 中)的文件作为文件名的一部分。 并在相邻单元格(单元格 G3)中打印该计数。 它按预期工作。 我的问题是我需要整个范围的结果。 字符串范围是从 pivot 表创建的。
我尝试只是复制代码并修改参考单元格,这很有效。 但是范围可以从几个字符串到 70+,我相信有比运行代码 70+ 次更有效和更清洁的方法。
Dim FolderPath As String, path As String, count As Integer
FolderPath = "C:\Test\PJC"
path = FolderPath & "\*" & Range("F3") & "*.xml"
FileName = Dir(path)
Do While FileName <> ""
count = count + 1
FileName = Dir()
Loop
Range("G3").Value = count
在 Range 上进行迭代可以如下实现:
Sub IterateRange()
Dim rng As Range, cell As Range
Dim myWs As Worksheet
Set myWs = Application.Worksheets("sheet1")
Set rng = myWs.Range("A1:A6")
For Each cell In rng
MsgBox cell.Value
Next cell
End Sub
通常使用 Worksheet 的 .Cells 属性进行迭代可能更直接,它可能如下所示:
Sub IterateRange()
Dim i As Long
Dim myWs As Worksheet
Set myWs = Application.Worksheets("Sheet1")
for i=1 to 6
MsgBox myWs.Cells(i, 1)
next i
End Sub
对于您的示例,如果您有要在范围 F3:F73 中检查的字符串,并且计数结果应该在范围 G3:G73 中,则您要查找的循环可能如下所示:
Sub Example()
Dim FolderPath As String, path As String, count As Integer, i As Integer
Dim myWs As Worksheet
Set myWs = Application.Worksheets("Sheet1")
For i = 3 To 73
count=0
FolderPath = "C:\Test\PJC"
path = FolderPath & "\*" & myWs.Cells(i, 6) & "*.xml"
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
myWs.Cells(i, 7) = count
Next i
End Sub
为了让循环在最后一行输入字符串后自动停止,只需添加
if myWs.Cells(i, 6)="" then
exit for
end if
行之间 For i = 3 To 73 and count=0
猜猜这会成功。 我把你的代码放在一个For
循环中。
我将起始行定义为第 3 行。
EndRange
将搜索 F 列中的最后一个值。 For 循环将从StartRange
迭代到EndRange
值。 我还进行了计数以打印 G 列中每个循环的计数变量的结果。
Sub LoopRange()
Dim FolderPath As String, path As String, count As Integer
Dim StartRange As Long, EndRange As Long
StartRange = 3 'Row = 3 for start
EndRange = Cells(Rows.count, "F").End(xlUp).Row 'Find last row in column F
For i = StartRange To EndRange 'Loop from start to end value
FolderPath = "C:\Test\PJC"
path = FolderPath & "\*" & Range(Cells(i, "F"), Cells(i, "F")) & "*.xml" 'Take the value from row i and column F in the loop.
Filename = Dir(path)
Do While Filename <> ""
count = count + 1
Filename = Dir()
Loop
Range(Cells(i, "G"), Cells(i, "G")).Value = count 'Print the count
Next i
End Sub
你有其他选择:
' One line solution, but can count all files only, without wildcards
Debug.Print CreateObject("Scripting.FileSystemObject").GetFolder("C:\temp\").Files.count
' Counting all *.pdf files in C:\temp
FolderPath = "\\temp\\"
Path = "pdf"
Dim objWMIService As Object
Dim objFiles As Object
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set objFiles = objWMIService.ExecQuery("Select * from CIM_DataFile where Path = '" & FolderPath & "' and Extension = '" & Path & "'")
Debug.Print "Files count: ", objFiles.Count
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.