我之前没有使用过VBA,但我找到了一个可以计算我需要的示例/工作工作簿。我把它放到我正在处理的工作簿中,但问题是我需要按行号设置数据范围并保持列静态,虽然我已经尝试过但不知道怎么做。这是我发现的代码工作正常,但只有静态范围。
Sub UpdatePairStats()
Dim LRange As Variant
Dim LRows As Long
Dim LCols As Long
Dim C As New Collection
Dim LItem As Long
Dim LDesc As String
Dim Counts(10000, 4) As String
Dim i As Long, j As Long, k As Long
On Error Resume Next
'Select sheet where data resides
Sheets("Draw Data").Select
'Data range (where draw information resides)
LRange = Range("C2:H1151")
LRows = UBound(LRange, 1)
LCols = UBound(LRange, 2)
'Loop through each row in LRange (find pairs)
For i = 1 To LRows
'j and k create the pairs
For j = 1 To LCols - 1
For k = j + 1 To LCols
'Separate pairs with a "." character (smaller number first)
If LRange(i, j) < LRange(i, k) Then
LDesc = LRange(i, j) & "." & LRange(i, k)
Else
LDesc = LRange(i, k) & "." & LRange(i, j)
End If
'Add new item to collection ("on error resume next" is
'required above in this procedure because of this line of code)
C.Add C.Count + 1, LDesc
'Retrieve indexnumber of new item
LItem = C(LDesc)
'Add pair information to new item
If Counts(LItem, 0) = "" Then
Counts(LItem, 0) = LDesc
Counts(LItem, 1) = LRange(i, j)
Counts(LItem, 2) = LRange(i, k)
End If
'Increment stats counter
If Counts(LItem, 3) = "" Then
Counts(LItem, 3) = "1"
Else
Counts(LItem, 3) = CStr(CInt(Counts(LItem, 3)) + 1)
End If
Next k
Next j
Next i
'Paste pairs onto sheet called PairStats
Sheets("PairStats").Select
Cells.Select
Selection.Clear
Cells(1, 1).Resize(C.Count, 4) = Counts
'Format headings
Range("A1").FormulaR1C1 = "'Number1.Number2"
Range("B1").FormulaR1C1 = "'Number1"
Range("C1").FormulaR1C1 = "'Number2"Range("D1").FormulaR1C1 = "'Occurrences"
Range("A1:D1").Select
Selection.Font.Bold = True
Selection.Font.Underline = xlUnderlineStyleSingle
Columns("A:D").EntireColumn.AutoFit
Range("F1").Select
Range("F1").FormulaR1C1 = "Last Updated on " & Now()
Sheets("Pairs").Select
MsgBox "Pair statistics have been updated."
End Sub
我需要设置的范围是
'Data range (where draw information resides)
LRange = Range("C2:H1151")
通过使用INDIRECT
从两个单独的单元格中获取行值但我想知道如何在VBA中实现相同类型的操作,我有其他计算工作正常(不在VBA中)。我正在使用的公式是
=IFERROR(FREQUENCY(INDIRECT("'Draw Data'!$C"&B2&":$H"&B3),$N$3:$N$13),0)
我读过INDIRECT不能在VBA中使用但是有一些简单的代码可以做同样的工作吗?
答案 0 :(得分:1)
首先,你需要知道数据的最后一行,你可以通过以下方式来实现:
Dim LRwithdata As Long
With Sheets("Draw Data")
LRwithdata = .Range("C:H").Find("*", , , , , xlPrevious).Row
LRange = .Range("C2:H" & LRwithdata)
End With
' rest of your code here
编辑1:如果行被引用到其他单元格
With Sheets("Draw Data")
LRange = .Range("C" & .Range("B2"), "H" & .Range("B3"))
End With
关键是要熟悉范围语法并在引用范围时相应地应用它。
您也可以查看以下链接,以便改进编码: