AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 77294895
Accepted
Shiela
Shiela
Asked: 2023-10-15 08:05:06 +0800 CST2023-10-15 08:05:06 +0800 CST 2023-10-15 08:05:06 +0800 CST

Obtenha o tempo total de uma exibição de coluna ListBox por alteração de ComboBox

  • 772

Tenho aqui um trecho de código para o evento de alteração do ComboBox4. Como você pode ver nos dados abaixo (formato de imagem excel), existe uma coluna para Tempo que tem meu formato preferido de “hh:mm:ss”. Estou tentando obter a soma da coluna tempo no ListBox (resultado mostrado no Label1 do Form). O resultado abaixo não está obtendo a soma correta.

Forma

Forma

Imagem de planilha do Excel (os espaços em branco têm uma finalidade) Imagem da planilha

Aqui estão os dados brutos da imagem acima:

Col. A         Col. B      Col. E       Col. G    Col. J           Col. L
YEAR      || NAME   || Total Time   || COLOR    || MONTH        || SHAPE
2023      || LINA   || 0:00:15      || GREEN    || AUGUST       || HEART
2023      || LINA   || 0:00:07      || GREEN    || SEPTEMBER    || CIRCLE
2024      || GARY   || 0:00:01      || GREEN    || SEPTEMBER    || DIAMOND
2024      || GARY   || 0:00:02      || GREEN    || SEPTEMBER    || RECTANGLE
2024      || GARY   || 0:00:15      || RED      || AUGUST       || OVAL
2023      || GARY   || 0:00:07      || RED      || AUGUST       || RECTANGLE
2023      || GARY   || 0:00:01      || GREEN    || AUGUST       || SQUARE
2024      || GARY   || 0:00:02      || GREEN    || SEPTEMBER    || STAR
2024      || TOM    || 0:00:15      || RED      || AUGUST       || HEART
2024      || TOM    || 0:00:07      || RED      || SEPTEMBER    || CIRCLE
2024      || TOM    || 0:00:01      || RED      || SEPTEMBER    || DIAMOND
2024      || TOM    || 0:00:02      || YELLOW   || SEPTEMBER    || OVAL
2024      || TOM    || 0:00:15      || YELLOW   || OCTOBER      || RECTANGLE
2024      || TOM    || 0:00:07      || YELLOW   || OCTOBER      || CIRCLE
2024      || TOM    || 0:00:01      || YELLOW   || OCTOBER      || SQUARE
2024      || TOM    || 0:00:02      || YELLOW   || OCTOBER      || STAR
2024      || TOM    || 0:00:15      || YELLOW   || OCTOBER      || STAR
2024      || TOM    || 0:00:07      || BLUE     || OCTOBER      || SQUARE

Aqui está o código do ComboBox4:

Option Explicit
Private Sub ComboBox4_Change()
    If Not ComboBox4.Value = "" Then
        Dim ws As Worksheet, rng As Range, count As Long, K As Long
        Dim arrData, arrList(), i As Long, j As Long
        Set ws = Worksheets("Sheet1")
        
        Dim countT As Date 'declared the variable here
        
        Set rng = ws.Range("A1:L" & ws.Cells(Rows.count, "B").End(xlUp).Row)
        arrData = rng.Value
        count = WorksheetFunction.CountIfs(rng.Columns(1), CStr(ComboBox2.Value), rng.Columns(2), ComboBox1.Value, rng.Columns(7), ComboBox3.Value, rng.Columns(10), ComboBox4.Value)
        ReDim arrList(1 To count + 1, 1 To UBound(arrData, 2))
        For j = 1 To UBound(arrData, 2)
            arrList(1, j) = arrData(1, j) 'header
        Next
        K = 1
                
        For i = 2 To UBound(arrData)
            If arrData(i, 2) = ComboBox1.Value And arrData(i, 1) = CStr(ComboBox2.Value) _
                And arrData(i, 7) = ComboBox3.Value And arrData(i, 10) = ComboBox4.Value Then
                K = K + 1
                
                countT = 0
                
                For j = 1 To UBound(arrData, 2)
                
                    countT = countT + arrData(i, 5) 'trying to get their total sum
                    
                    arrList(K, 5) = Format(arrData(i, 5), "hh:mm:ss")
                Next
                Label1.Caption = Format(CDate(countT), "hh:mm:ss") 'show total sum in this label in the form of hh:mm:ss
            End If
        Next
        With Me.ListBox1
            .ColumnHeads = False
            .ColumnWidths = "0,0,0,0,40,0,0,0,0,0,0,0"
            .ColumnCount = UBound(arrData, 2)
            .List = arrList
        End With
    End If
End Sub

Agradeço antecipadamente...

excel
  • 1 1 respostas
  • 34 Views

1 respostas

  • Voted
  1. Best Answer
    taller
    2023-10-15T08:46:08+08:002023-10-15T08:46:08+08:00
    • For j = 1 To UBound(arrData, 2)deve ser eliminado do loop For aninhado.
    • Inicialize countTantes de entrar no loop For e atualize label1após sair do loop.

    Se você está curioso para saber como o tempo 0:03:00é determinado, aqui está a explicação com seu código:

    • A variável countT é inicializada e o rótulo é atualizado dentro do loop aninhado externo (loop for i).
    • O valor exibido no rótulo corresponde ao último valor que atende à condição if, que é “0:0:15”.
    • O loop interno (for j loop) é executado 12 vezes (UBound(arrData,2) é 12), então countT acumula até 180 segundos (12 * 15), o que equivale a "0:03:00"
    Option Explicit
    Private Sub ComboBox4_Change()
        If Not ComboBox4.Value = "" Then
            Dim ws As Worksheet, rng As Range, count As Long, K As Long
            Dim arrData, arrList(), i As Long, j As Long
            Set ws = Worksheets("Sheet1")
            Dim countT As Date 'declared the variable here
            Set rng = ws.Range("A1:L" & ws.Cells(Rows.count, "B").End(xlUp).Row)
            arrData = rng.Value
            count = WorksheetFunction.CountIfs(rng.Columns(1), CStr(ComboBox2.Value), rng.Columns(2), ComboBox1.Value, rng.Columns(7), ComboBox3.Value, rng.Columns(10), ComboBox4.Value)
            ReDim arrList(1 To count + 1, 1 To UBound(arrData, 2))
            For j = 1 To UBound(arrData, 2)
                arrList(1, j) = arrData(1, j) 'header
            Next
            K = 1
            countT = 0 ' ** Add
            For i = 2 To UBound(arrData)
                If arrData(i, 2) = ComboBox1.Value And _
                    arrData(i, 1) = CStr(ComboBox2.Value) And _
                    arrData(i, 7) = ComboBox3.Value And _
                    arrData(i, 10) = ComboBox4.Value Then
                    K = K + 1
                    ' countT = 0 ' ** Remove
                    ' For j = 1 To UBound(arrData, 2) ' ** Remove
                    countT = countT + arrData(i, 5) 'trying to get their total sum
                    arrList(K, 5) = Format(arrData(i, 5), "hh:mm:ss")
                    ' Next ' ** Remove
                    ' Label1.Caption = Format(CDate(countT), "hh:mm:ss") ' ** Remove
                End If
            Next
            Me.Label1.Caption = Format(CDate(countT), "hh:mm:ss") 'show total sum in this label in the form of hh:mm:ss
            With Me.ListBox1
                .ColumnHeads = False
                .ColumnWidths = "0,0,0,0,40,0,0,0,0,0,0,0"
                .ColumnCount = UBound(arrData, 2)
                .List = arrList
            End With
        End If
    End Sub
    
    • 1

relate perguntas

  • Como posso retornar linhas específicas onde EXISTE uma taxa no contrato listado, mas NÃO há taxa no sistema?

  • adicionar automaticamente um campo de referência em uma tabela quando alguns valores são repetidos?

  • percorrer a coluna com a alteração do endereço da célula

  • Pesquise uma string e os valores de saída correspondentes a essa string

  • Existe uma maneira no Excel de contar as ocorrências de um texto específico em uma string, mas também incluir o caractere anterior?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve