热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

为什么我的单元格值在新工作簿中循环时会堆积

我是VBA的新手。我一直在使用for循环将计数添加到我的摘要页面,但是

我是VBA的新手。我一直在使用for循环将计数添加到我的摘要页面,但是当它循环遍历多个工作簿时,摘要页面也不断增加,因为它也累加了上一个工作簿的价值。

我如何指定要计数的计数器并添加到其特定的摘要页面?

例如第一个工作簿摘要页数为10,下一个工作簿工作簿数为该工作簿数的10+。预先感谢!

Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim x As Integer
Dim wash_count As Integer
'Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationmanual
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xls*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(Filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
For Each ws In wb.Sheets
If ws.Name <> "Summary" Then
For x = 5 To 74
If ws.Cells(x,2).Value = "Wash" And (ws.Cells(x,4).Value = "T") Then
wash_count = wash_count + 1
End If
Next x
End If
Next ws
wb.Sheets("Summary").Range("D6") = wash_count
'Save and Close Workbook
wb.Close SaveChanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub



您不重置计数器:

'...
wb.Sheets("Summary").Range("D6") = wash_count
wash_count = 0 '<


推荐阅读
author-avatar
Cher麻花
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有