Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 91855

Why does my cell value stack up as it loops through new workbooks

$
0
0

I'm new to VBA. I've been using for loop to add counts to my summary page, but as it loops through the multiple workbooks, the summary page keeps increasing as it adds up the value of the previous workbook too.

How do I specify the counter to just count and add into their specific summary page?

E.g. first workbook summary page count is 10, the next workbook workbook will be 10+ that workbook's count. Thanks in advance!

    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

Viewing all articles
Browse latest Browse all 91855

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>