将非空白单元格的计数添加到前一个值VBA的计数

我是新的Excel VBA,我想帮助我面临的问题。

在这里输入图像说明

我在上面的链接中列举了一个小例子。 我想要的是在定义的范围内每列中的字符数。 但是,如果存在空白单元格,则空白单元格将被计入前面的非空白值。 在例子1中:单元3,4是空的,它们的前一个非空值是R.所以R的计数变成4.单元6也是空的,因此被加到Y的前一个非空值。 所以Y的数量是2。

在示例2中:单元格1,2是空的,但是它们没有任何先前的非空值,因此它们不被计数。 另外,单元格4,5,6是空的。 但是,它们有一个前面的非空白值Y.所以Y的计数是4

有人可以帮我在VBA中编码吗?

假设你有A列的行索引和B列的数据,并且工作表中的数据从第3行开始(如图所示),我会build议下面的代码:

Sub test() Dim rowNum As Integer Dim prevRowData As String Dim rCount, yCount rowNum = 3 prevRowData = "" rCount = 0 yCount = 0 Do While Trim(Range("A" & rowNum).Value) <> "" Select Case (Trim(Range("B" & rowNum).Value)) Case "R" rCount = rCount + 1 prevRowData = "R" Case "Y" yCount = yCount + 1 prevRowData = "Y" Case "" If prevRowData = "R" Then rCount = rCount + 1 ElseIf prevRowData = "Y" Then yCount = yCount + 1 End If End Select rowNum = rowNum + 1 Loop Range("A" & (rowNum + 1)).Value = "Count of R:" & rCount Range("A" & (rowNum + 2)).Value = "Count of y:" & yCount End Sub 

像这样的事情会做到这一点。 需要注意的是,这只会到最后一行使用,所以你的第六行将不会被计算,因为第五行以外没有数据。如果你知道那一行,可以用行号replacelastRow,不知道你怎么知道最后一个应该被计算的空白行。

在你的VBA IDE中,进入工具菜单并select引用。 select“Microstoft ActiveX数据对象2.8库”。

我们将使用一个ADODBlogging集来存储我们find的数据。

这假设您的列表在Sheet1上,数据在列A中。它将在读取的数据下面写出摘要。

 Private Sub CommandButton1_Click() Dim rs As New ADODB.Recordset Dim ws As Excel.Worksheet Set ws = ActiveWorkbook.Sheets("Sheet1") Dim lastRow As Long Dim lRow As Long Dim szLastData As String 'Add fields to your recordset for storing data. With rs .Fields.Append "Value", adChar, 25 .Fields.Append "Count", adInteger .Open End With 'This is getting the last used row in column A lastRow = ws.Cells(ws.Rows.count, "A").End(xlUp).Row 'Loop through the rows lRow = 1 Do While lRow <= lastRow 'Update the value we will search for in out rs if there is data in the current row If ws.Range("A" & lRow).Value <> "" Then szLastData = ws.Range("A" & lRow).Value End If 'Check if this is already data that we are counting rs.Filter = "" rs.Filter = "Value='" & szLastData & "'" If rs.RecordCount = 0 Then 'If this is new data, add a new row for it rs.AddNew rs.Fields("Value").Value = ws.Range("A" & lRow).Value rs.Fields("Count").Value = 1 rs.Update Else 'If we get here, we already have this data. 'Increment the count by 1 rs.Fields("Count").Value = rs.Fields("Count").Value + 1 rs.Update End If lRow = lRow + 1 Loop 'Remove the filer and move to the first record in the rs rs.Filter = "" rs.MoveFirst 'Move down a row lRow = lRow + 1 'Loop through the data we found and write a summary Do While rs.EOF = False ws.Range("A" & lRow).Value = rs.Fields("Value").Value ws.Range("B" & lRow).Value = rs.Fields("Count").Value lRow = lRow + 1 rs.MoveNext Loop End sub