编辑将来可能对其他人有帮助的问题。
在给定的一系列数字中,出现在给定数字之前和之后的值将被分配到各自的表格,如附图中所示。
数字系列如下。即5作为第一个输入的数字,3是最后一个。因此4在2之前,3在2之后。
系列 3 2 4 8 0 8 7 3 8 7 0 0 4 9 6 3 9 7 4 5
正在使用的代码要点:
'Private Sub CommandButton1_Click()
Dim cell As Variant
myrange = Range("B1:B30").Value
For each cell in myRange
if (cell=range("H2")) then
'save the value of current cell if it matches
range("h3")=cell.offset(1,0)
if (cell.offset(1,0) = range("h3"))
'Count offset value (Value in cell.offset(1,0)) each time it appears before current cell (cell as in cell in my range)
endif
end if
next cell
end sub
该示例是正在完成的内容的缩短版本。欢迎采用更有效的方法。
提前致谢。 :)
修改:添加了预期Output Snippet
答案 0 :(得分:0)
Sub Tester()
Dim arr, r, b, a
arr = Range("A1:A20").Value
Range("D4").Resize(10, 10).ClearContents
Range("D17").Resize(10, 10).ClearContents
For r = 1 To UBound(arr, 1) - 1
b = arr(r, 1)
a = arr(r + 1, 1)
With Range("D4")
.Offset(b, a).Value = .Offset(b, a).Value + 1
End With
With Range("D17")
.Offset(a, b).Value = .Offset(a, b).Value + 1
End With
Next r
End Sub
答案 1 :(得分:0)
现在我知道'之前&在'定义与我假设的相反之后,我更改了代码以生成正确的结果。
Option Explicit
Private Sub CommandButton1_Click()
Dim ws As Worksheet
Dim lLastRow As Long
Dim lRow As Long
Set ws = ActiveWorkbook.Sheets("BefAfter")
ws.Activate
' Get last row number
lLastRow = Cells.Find(What:="*", After:=Range("A1"), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
' Clear BEFORE counts
Range("H3:Q12").Select
Selection.ClearContents
' Clear AFTER counts
Range("H18:Q27").Select
Selection.ClearContents
For lRow = 2 To lLastRow
' Get all the after #'s
If lRow > 2 Then
ws.Cells(18 + ws.Cells(lRow, 2), 8 + ws.Cells(lRow - 1, 2)) = ws.Cells(18 + ws.Cells(lRow, 2), 8 + ws.Cells(lRow - 1, 2)) + 1
End If
' Get all the before #'s
If lRow < lLastRow Then
ws.Cells(3 + ws.Cells(lRow, 2), 8 + ws.Cells(lRow + 1, 2)) = ws.Cells(3 + ws.Cells(lRow, 2), 8 + ws.Cells(lRow + 1, 2)) + 1
End If
Next lRow
'MsgBox "Finished"
End Sub