简体   繁体   中英

Excel VBA - Select cells based on the value of another cell and then Autosum - Is it possible

Please can you help

I am trying to use the autosum feature in the highlighted boxes as per the example below (these are shown in yellow for illustration purposes only)

In column A the word "Total" appears and this is the indication that the autosum needs to be used in columns L,M & N

The data in each section varies in length so unfortunately I am not able just to record a macro to achieve this.

I need to use VBA coding, so if you are able to help it would be greatly appreciated.

OTIF示例文件

Thanks

Regards Steve

Dim ws As Excel.Worksheet
Dim lRow As Long
Dim lStartSection As Long

Set ws = Application.Sheets("Sheet1")
lRow = 3
lStartSection = 0

'Loop through the used range in the spreadsheet
Do While lRow <= ws.UsedRange.Rows.Count

    'If we are at the start of a section record the row.
    If lStartSection = 0 And ws.Range("A" & lRow).Value <> "" Then
        lStartSection = lRow
    End If

    'Check if we are at the bottom of a section
    If ws.Range("A" & lRow).Value = "Total" Then
        ws.Range("L" & lRow).Value = "=SUM(L" & lStartSection & ":L" & lRow - 1 & ")"
        ws.Range("M" & lRow).Value = "=SUM(M" & lStartSection & ":M" & lRow - 1 & ")"
        ws.Range("N" & lRow).Value = "=SUM(N" & lStartSection & ":N" & lRow - 1 & ")"

        'Set this back to zero so we know that we are no longer in a section
        lStartSection = 0
    End If

lRow = lRow + 1
Loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM