【问题标题】:VBA to Count the value in column and fill the table in another sheetVBA计算列中的值并将表格填充到另一张表中
【发布时间】:2017-12-02 00:01:52
【问题描述】:

我有两个 Sheets , sheet1 和 sheet2。

我有一张表,其中包含周数、延迟、好的、延迟的百分比和 OK 的百分比。

在表 1 中,我正在寻找列 T,并计算列中“1”的数量。同样,我查找列 U 并计算列中“0”的数量。

Count 值必须填写在表格的 sheet2 中查看一周。我在 sheet1 的 AX 列中有我的一周。

我使用了类似 Countif 的公式来计算两列中 1 的数量。 有人可以指导我如何在 VBA 中做到这一点,计算列中的值并将结果粘贴到另一张表的表格中。我很惊讶如何从编码开始。这是我的 sheet1,我必须计算列 t 和 u 中 1 的数量

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    为了解决这个问题,我们必须使用几个循环。首先,我们必须做一个外部循环来遍历 sheet2 中的周数,然后嵌入到该循环中,我们必须查看 sheet1 中的每一行以查看它是否与 sheet2 中的周匹配,并查看列 T = 1 和如果列 U = 0。代码创建一个计数器,每当 T 中的一行等于 1 时,T 就增加一,并且每次 U = 0 中的一行时,对 U 执行相同的操作。

    Sub test()
    Dim col As Range
    Dim row As Range
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim T As Integer
    Dim U As Integer
    Dim wk As String
    
    Set sh1 = Sheets("Sheet1")
    Set sh2 = Sheets("Sheet2")
    
    
    
    For Each col In sh2.Columns 'This loops through all populated columns in row one
        If sh2.Cells(1, col.Column).Value = "" Then
            Exit For
        End If
    
        wk = sh2.Cells(1, col.Column).Value
    
        For Each rw In sh1.Rows
            If sh1.Cells(rw.row, 50).Value = "" Then
                Exit For
            End If
    
            If sh1.Cells(rw.row, 50) = wk And sh1.Cells(rw.row, 20) = 1 Then
                T = T + 1
            End If
    
            If sh1.Cells(rw.row, 50) = wk And sh1.Cells(rw.row, 21) = 0 Then
                U = U + 1
            End If
        Next rw
    
    sh2.Cells(2, col.Column) = T 'put counters into 2nd and 3rd row under each week, you can adjust this to put the number in a different cell.
    sh2.Cells(3, col.Column) = U
    
    T = 0 'reset counters to start looking at next week.
    U = 0
    
    Next col
    
    End Sub
    

    由于某种原因,我无法查看您刚刚上传的图片。您可能需要调整我的代码以适应您的 excel 文件的具体情况。这对您来说将是一个很好的 VBA 练习。我的代码假设 sheet2 的周数跨列,它们之间没有任何空白单元格。 vba 将代码放在相应周数下的第 2 行和第 3 行中。您可以通过更改 cmets 中指示的代码来更改此设置。

    【讨论】:

    • 如果你不介意,你能告诉我不使用函数我们是怎么做的吗?
    • 另外,上面的 Counts 用于列中的值,但它不会查找周数并在 sheet2 中相应地填写表格。
    • 有不想使用countif函数的原因吗?我认为这将是最简单的方法。我想您可以使用 if 语句遍历 I 列中的每一行,以查看它是否为 1。但这将是非常低效和不必要的复杂。
    • 它不寻找 CW。并将结果粘贴到 sheet2 中。
    • 如果您可以查看我的图像,它应该检查 sheet1 中的 CW,然后将 Count 值相应地发布到 sheet2。 @jarom
    猜你喜欢
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 2019-04-21
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    相关资源
    最近更新 更多