Excel 2013 VBA - найдите конкретный заголовок и суммируйте все значения ниже - PullRequest
0 голосов
/ 02 октября 2018

Проблема - я хочу найти конкретный заголовок [например.«Сумма без учета GST»] на листе, который не всегда находится в одном и том же месте, обычно в первых 5 строках.Затем я хочу суммировать все значения, начиная с 1 ячейки ниже, до последней ячейки, которая имеет значение (иногда только 1 ячейка, остальные 1000) и вставить отдельные значения в другую ws: SourceShtClm.Range ("D" & Last_Row) .Value

Я исследовал [ VBA - Найти столбец с определенным заголовком и найти сумму всех строк в этом столбце и нашел некоторый код, но я изо всех сил пытаюсь изменить его в соответствии со своими конкретными потребностями.

    Sub Coles_straight_consolidation()
'Coles Straight Claims Import Macro

Dim SourceWB As Workbook        'Coles Consolidate Promo Claims
Dim SourceShtClm As Worksheet
Dim SourceShtPCD As Worksheet
Dim SourceShtFrml As Worksheet
Dim SourceShtMcrRng As Range
Dim SourceShtFrmlRng As Range
Dim FPath As String             'csv Folder containing raw data export
Dim fCSV As String
Dim wbCSV As Workbook
Dim wbMST As Workbook
Dim FiName As String            'saves promo claims file to new xls file
Dim FiPath As String
Dim StartTime As Double         'time elapsed counter
Dim MinutesElapsed As String
Dim xColIndex As Integer
Dim xRowIndex As Integer
Dim ws As Worksheet
Dim shtSrc As Worksheet
Dim f As Range



    StartTime = Timer           'starts timer - Remember time when macro starts

    NeedForSpeed                'speeds up macro

Set SourceWB = ThisWorkbook     'Set workbook

Set SourceShtMcr = SourceWB.Sheets("Macro")                 'set worksheets
Set SourceShtClm = SourceWB.Sheets("Claim Summary")
Set SourceShtPCD = SourceWB.Sheets("Promo Claim Details")



FPath = ThisWorkbook.Path & "\csv_macro\"                                 'path to CSV files, include the final \
fCSV = Dir(FPath & "*.csv")                                         'start the CSV file listing

    On Error Resume Next
    Do While fCSV <> ""
        Set wbCSV = Workbooks.Open(FPath & fCSV)                'opens workbook

        Last_Row = SourceShtClm.Range("C" & Rows.Count).End(xlUp).Row + 1

        SourceShtClm.Range("C" & Last_Row).Value = Range("G2").Value
        SourceShtClm.Range("F" & Last_Row).Value = Range("L2").Value
        SourceShtClm.Range("G" & Last_Row).Value = Range("Q2").Value
        SourceShtClm.Range("H" & Last_Row).Value = Range("I2").Value
        SourceShtClm.Range("I" & Last_Row).Value = Range("J2").Value

        'Amount Excluding GST


        Set shtSrc = wbCSV.Sheets(1)

        Set f = shtSrc.UsedRange.Find(What:="Amount Excluding GST", After:=shtSrc.Range("A1"), _
                              LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows)

        If Not f Is Nothing Then

            Set pRng = shtSrc.Range(f.Offset(1, 0), _
                            shtSrc.Cells(shtSrc.Rows.Count, f.Column).End(xlUp))

        Else

            MsgBox "Required header 'Amount Excluding GST' not found!"

        End If

        SourceShtClm.Range("D" & Last_Row).Value = Application.WorksheetFunction.Sum(pRng)



        'Amount Including GST
        'copy code from above


        wbCSV.Close SaveChanges:=False

        fCSV = Dir                  'ready next CSV


    Loop

    Set wbCSV = Nothing


        SourceWB.Activate
        SourceShtClm.Select
        'Columns("B:J").AutoFit             'Auto fits Columns - update as not all col need auto fit
        ActiveWorkbook.RefreshAll


    MinutesElapsed = Format((Timer - StartTime) / 86400, "hh:mm:ss")        'stops timer - Determine how many seconds code took to run

    MsgBox "This code ran successfully in " & MinutesElapsed, vbInformation & " Make sure to save file as MMM Straights"        'Msg box for elapsed time & Claims consldaited


    ResetSpeed

End Sub

1 Ответ

0 голосов
/ 02 октября 2018

Вот хороший общий подход для этого типа задач.Обратите внимание, что обычно рекомендуется убедиться, что Find() был успешным, прежде чем пытаться получить доступ к свойствам найденной ячейки ...

Dim shtSrc As Worksheet
Dim f As Range

Set shtSrc = wbCSV.Sheets(1)

Set f = shtSrc.UsedRange.Find(What:="Amount Excluding GST", After:=shtSrc.Range("A1"), _
                              LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows)

If Not f Is Nothing Then

    Set pRng = shtSrc.Range(f.Offset(1,0), _
                            shtSrc.Cells(shtSrc.Rows.Count, f.Column).End(xlUp))  

Else

    Msgbox "Required header 'Amount Excluding GST' not found!"

End If
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...