如何根据条件在Excel中选择单元格范围?

时间:2019-03-16 22:51:24

标签: excel vba

我需要在工作表1中选择与在工作簿的工作表2中选择的零件编号相对应的需求范围。到目前为止,我已经编写了宏,以便在第2号表中选择相同的零件号时自动在工作表1中选择零件号。但是,我在选择与要作为基准的零件号相对应的范围时遇到了麻烦我的计算谁能告诉我如何选择范围?

Public Sub calculation()
    Dim x As Variant
    Dim rng As Range
    Dim i As Variant
    Dim j As Integer
    Dim findcell As Range
    Dim a_1 As Range
    Dim b_1 As Range
    Dim rnge As Range

    Worksheets("Sheet2").Activate
    x = Worksheets("Sheet2").Range("C3").Value
    Worksheets("Sheet1").Activate
    Set rng = Worksheets("Sheet1").Range("A2:A26")        

    For Each i In rng
        If x = i Then
            Set findcell = i
        End If
    Next i

    j = findcell.Select

    Set a_1 = ActiveCell.Offset(0, 1)
    Set b_1 = ActiveCell.Offset(0, 66)

    Worksheets("Sheet2").Range("C9").Value "=AVERAGE(Sheet1!"a_1.Address":"b_1.Address")"
End Sub

enter image description here

1 个答案:

答案 0 :(得分:0)

应该能够执行以下操作:

Public Sub calculation()

    Dim f As Range

    Set f = Worksheets("Sheet1").Range("A2:A26").Find( _
               what:=Worksheets("Sheet2").Range("C3").Value, _
               lookat:=xlWhole)

    With Worksheets("Sheet2").Range("C9")
        If Not f Is Nothing Then
            .Formula = "=AVERAGE(Sheet1!" & f.Offset(0, 1).Resize(1, 66).Address & ")"
        Else
            .Value = "???"
        End If
    End With

End Sub