使用变量(不是单元格值)分配单元格号

时间:2019-07-20 01:42:11

标签: excel vba

我需要根据几个包含可变数据的工作簿上的相对单元格值来确定给定的单元格编号(例如C100)。一旦定义了两个这样的单元格编号(一个范围),我将需要这些单元格中包含的值的平均值。

这里是设置,可以正常运行。


'   Perform "FIND" function for the first case of "LOCAL PEAK". Note: Since column D is composed of the above formula, the
'   find function only recognizes the VALUES in column E
    Set found = ActiveSheet.Cells.Find(What:="LOCAL PEAK", After:=[e1], LookIn:=xlValues, _
        LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=True)

' Assign the row number associated with the first instance of "LOCAL PEAK" to the variable "StaticRow"
    If Not found Is Nothing Then StaticRow = found.Row

' Assign the value in the cell of the force column associated with the first instance of "LOCAL PEAK" to the variable "SForce"
    SForce = Cells(StaticRow, 3).Value

' Assign the value in the cell of the position column associated with the first instance of "LOCAL PEAK" to the variable "InitialPos"
    InitialPos = Cells(StaticRow, 2).Value

' Assign the rows for Kinetic Friction calculation
    KineticRowA = StaticRow + 60
    KineticRowB = StaticRow + 300

继续我尝试过的操作不起作用:

    CellA = Cells(KineticRowA, 3)
    CellB = Cells(KineticRowB, 3)

KForce = WorksheetFunction.Average(Range(CellA, CellB))

上述方法将VALUES分配给变量CellA和CellB,而不是单元格位置。

这下一个完全无效的方法:)

KForce = WorksheetFunction.Average(Range("CKineticRowA:CKineticRowB"))

谢谢!

1 个答案:

答案 0 :(得分:3)

如果要为范围变量分配值,则缺少Set

Dim CellA As Range, CellB As Range, ws As Worksheet

Set ws = ActiveSheet
Set CellA = ws.Cells(KineticRowA, 3)
Set CellB = ws.Cells(KineticRowB, 3)

KForce = WorksheetFunction.Average(ws.Range(CellA, CellB))