【发布时间】:2018-05-30 14:19:10
【问题描述】:
我在 VBA 中创建了一个宏,它应该检查 Excel 工作表上的零件编号与文件目录中零件的文件名。脚本是这样的:
Sub scanDirectory()
Dim path As String
Dim currentPath As String
Dim nameOfFile As String
Dim counterA As Integer
Dim success As Integer
Dim endTester As String
Dim draw As Integer
'put the path to your folder here along with an \
path = "\C:\Users\joe.blow\Documents\"
counterA = 8
Do Until counterA > 4294
nameOfFile = Sheets("Sheet0").Cells(counterA, 2)
currentPath = Dir(path)
success = 0
draw = 0
Do Until currentPath = vbNullString
Debug.Print currentPath
'Success for Model
endTester = nameOfFile + ".SLDPRT"
If currentPath = endTester Then
Sheets("Sheet0").Cells(counterA, 5) = "Y"
success = 1
End If
endTester = nameOfFile + ".sldprt"
If currentPath = endTester Then
Sheets("Sheet0").Cells(counterA, 5) = "Y"
success = 1
End If
'Success for Assembly
endTester = nameOfFile + ".SLDASM"
If currentPath = endTester Then
Sheets("Sheet0").Cells(counterA, 5) = "Y"
success = 1
End If
'Succees for Drawing
endTester = nameOfFile + ".SLDDRW"
If currentPath = endTester Then
Sheets("Sheet0").Cells(counterA, 6) = "Y"
draw = 1
End If
endTester = nameOfFile + ".slddrw"
If currentPath = endTester Then
Sheets("Sheet0").Cells(counterA, 6) = "Y"
draw = 1
End If
If draw = 0 Then
Sheets("Sheet0").Cells(counterA, 6) = "N"
End If
If success = 0 Then
Sheets("Sheet0").Cells(counterA, 5) = "N"
End If
currentPath = Dir()
Loop
counterA = counterA + 1
Loop 'NextLine' End Sub
它的工作原理是逐行检查每个单元格与整个文件树,检查文件扩展名的每个排列。然后,如果文件存在或不存在相应的“Y”或“N”,它将放入一个空列。它同时对模型和图纸执行此操作。
它适用于 1 小时,那么即使它是“无响应”,它也会完成运行。有没有更好的方法来运行它,这样它就不会花费那么长时间或
【问题讨论】:
-
一个提示是在代码的开头添加
Application.ScreenUpdating = False,然后在末尾添加Application.ScreenUpdating = True。见here for some more pointers on speeding up your code -
您绝对可以清理代码以提高效率。你有很多多余的 if 语句。我会在稍后发布答案。
-
为什么不将所有文件名导入到工作表中,然后从那里对数据进行排序,它会比即时执行要快得多:stackoverflow.com/a/44068091/5202456(这段代码甚至计算了它花费的时间导入数据)
标签: vba excel optimization