Как мне получить только целое число, чтобы появиться только в окончательной книге - PullRequest
0 голосов
/ 07 ноября 2019

Привет, у меня есть этот код, который подсчитывает, сколько раз «Т» появляется в различных книгах, где каждая книга имеет около 10-12 листов. главная цель - получить в окончательной рабочей книге общее число раз, которое T появилось при циклическом просмотре файла.

Private Sub CommandButton3_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 StrConv(ws.Cells(x, 2).Value, vbProperCase) = "Wash" And StrConv(ws.Cells(x, 4).Value, vbProperCase) = "T" Then 'added the StrConv to make sure you don't loose a case just because it was written in capital or lowercase letters
                        wash_count = wash_count + 1
                    End If
                Next x
             End If
        Next ws

        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

Проблема теперь состоит в том, что предыдущие рабочие книги с листами также назывались «Сводка». получает счетчик внутри тоже. прямо сейчас код получает итоговое значение в последней книге, но как мне избежать его появления на страницах сводки в предыдущих книгах, я хочу направить все значения только в итоговую книгу. Заранее спасибо

1 Ответ

0 голосов
/ 07 ноября 2019

Вы можете сделать что-то вроде этого:

Dim ColFiles As New Collection, i As Long

'...
'...
'...

'collect the files first
myFile = Dir(myPath & myExtension)
Do While myFile <> ""
    ColFiles.Add myPath & myFile
    myFile = Dir()
Loop

'now loop over the collection
For i = 1 To ColFiles.Count

    Set wb = Workbooks.Open(ColFiles(i))
    'count things in wb

    'is this the last file?
    If i = ColFiles.Count Then
        wb.Sheets("Summary").Range("D6") = wash_count
        wb.Close True  'save
    Else
        wb.Close False 'no save
    End If

Next i
...