【问题标题】:Excel count target then output value in cellExcel计数目标然后在单元格中输出值
【发布时间】:2015-02-10 01:36:43
【问题描述】:

我有一个包含三张纸的工作簿(Dash、HT、RV。)

我正在尝试编写一个宏/函数来计算'Dash'中的值存在于工作表'RV'中的特定列中的次数,然后在'Dash'中的特定单元格中输出该值

我什至可以说“Dash”中的值是静态的并重复它(“Dash”中的变量永远不会改变,因为它是用户名列表)

在我的脑海中是这样的:在 Dash.B2 中的 sheet.RV 打印的 J 列中计算任何.variable.Dash...

我能够找到一个有效的 MsgBox 选项,但我必须手动输入每个用户名(这是一个 16 字符的名称(字符串)),然后一个 MsgBox 告诉我出现的情况。我希望在宏/函数中使用固定/静态用户名自动执行此选项,因为“RV”中的行数可能在 700 个条目到 23k 个条目之间变化

MsgBox 选项是:

Dim Count as Integer
Dim Target As String
Dim Cell as Object
Dim N As Integer

Sub Target_Count()
    Count = 0
    Target = InputBox("character(s) to find?")
    If Target = "" Then GoTo Done
        For Each Cell in Selection
            N = InStr(1, cell.Value, target)
            While N <> 0
                Count = count + 1
                N = InStr(n + 1, cell.Value, target)
            Wend
        Next Cell
    MsgBox count & " Occurrences of " & target
Done:
End Sub

我希望输入框目标是 'Dash.A1:8' 并且出现在 'Dash.B1:8' 中打印

【问题讨论】:

    标签: vba excel count


    【解决方案1】:

    您可以只使用countif() 公式而不是编写宏吗?假设您计算“破折号”所在的列是 RV 表格中的 B 列,然后在表格 Dash 的单元格中,公式为:

    =COUNTIF(RV!B:B,"dash")

    或者,如果您想改变计数的内容,只需将公式中的硬编码“破折号”替换为输入单元格地址即可。

    【讨论】:

      【解决方案2】:

      如果你想要 VBA,你可以使用它。随意调整。

      Sub Target_Count_2()
      Dim wb As Workbook
      Set wb = ThisWorkbook
      Dim Cell As Range
      Dim Count As Integer
      Dim LastRow As Long
      LastRow = wb.Worksheets("RV").Range("A1").SpecialCells(xlCellTypeLastCell).Row
      Dim strArr() As Variant
      strArr() = wb.Worksheets("RV").Range("J1:J" & LastRow).Value
      Dim i As Long
      Dim str As String
      
          For Each Cell In wb.Worksheets("Dash").Range("B1:B8")
              Count = 0
              str = Cell.Offset(, -1).Value2
              For i = LBound(strArr) To UBound(strArr)
                  If str = strArr(i, 1) Then Count = Count + 1
                  'If InStr(strArr(i, 1), str) > 0 Then Count = Count + 1
              Next
              Cell.Value2 = Count
          Next
      
      Set Cell = Nothing
      Set wb = Nothing
      End Sub
      

      请注意,str = strArr(i, 1) 将仅匹配单元格中的完整值,而 InStr(strArr(i, 1), str) &gt; 0 也将匹配单元格中的部分值。假设您正在单元格中查找值为"AAAB""AAA"。第一种方法不会在Count 中添加额外的1,而第二种方法会。

      【讨论】:

        猜你喜欢
        • 2011-02-03
        • 1970-01-01
        • 1970-01-01
        • 2017-04-17
        • 1970-01-01
        • 1970-01-01
        • 2020-02-15
        • 2023-04-05
        • 1970-01-01
        相关资源
        最近更新 更多