使用union数组时匹配期间出错

时间:2018-02-19 08:07:33

标签: excel vba excel-vba

我试图在非连续范围内获得最高值并打印其地址。我在Excel中使用了数据,如下图所示:

Sample image

我使用的VBA代码是:

Sub rngadd()

Dim r1 As Range, r2 As Range, newrng As Range
Dim dblmax As Double
Dim Xrng As Variant

Worksheets("sheet3").Activate
Set r1 = Range("A1:A5")
Set r2 = Range("A8:A12")
Set newrng = Union(r1, r2)
newrng.Select

dblmax = Application.WorksheetFunction.max(newrng)
Xrng = WorksheetFunction.Index(newrng, WorksheetFunction.Match(dblmax, newrng, 0)).address(False, False)
Worksheets(2).Range("D3").Value = dblmax
Worksheets(2).Range("E3").Value = Xrng

End Sub

我收到错误,因为运行时错误:

  

'1004'无法获取工作表函数类的匹配属性“

但如果我只为范围r1运行代码,我会得到图像中的预期结果:

Sample Image2

所以我发现由于使用了union而得到错误,当范围中断(非连续范围)时匹配无法执行。

我应该怎么做才能在不连续的范围内获得所需的结果,例如我在连续范围内得到的结果?

2 个答案:

答案 0 :(得分:2)

索引和匹配不会在非连续范围内工作。

您可以遍历单元格以查找最大值及其对应的单元格地址,如下所示...

Sub rngadd()

Dim r1 As Range, r2 As Range, newrng As Range, cell As Range
Dim cellAddress As String
Dim maxVal As Long

Worksheets("sheet3").Activate
Set r1 = Range("A1:A5")
Set r2 = Range("A8:A12")
Set newrng = Union(r1, r2)

For Each cell In newrng
    If cell.Value > maxVal Then
        maxVal = cell.Value
        cellAddress = cell.Address(0, 0)
    End If
Next cell

Worksheets(2).Range("D3").Value = maxVal
Worksheets(2).Range("E3").Value = cellAddress

End Sub

答案 1 :(得分:2)

使用Find()对象的Range方法:

Sub rngadd()

    Dim r1 As Range, r2 As Range, newrng As Range
    Dim dblmax As Double
    Dim Xrng As Range

    Worksheets("sheet3").Activate
    Set r1 = Range("A1:A5")
    Set r2 = Range("A8:A12")
    Set newrng = Union(r1, r2)
    newrng.Select

    dblmax = Application.WorksheetFunction.Max(newrng)
    Set Xrng = newrng.Find(what:=dblmax, lookat:=xlWhole, LookIn:=xlValues)
    Worksheets(2).Range("D3").Value = dblmax
    Worksheets(2).Range("E3").Value = Xrng.Address

End Sub

但是所有Activate / Select都是不好的做法,如果您事先已经知道了范围地址(正如您现在所做的那样),也可以避免使用Union()

所以请考虑以下重构:

Sub rngadd()
    Dim newrng As Range
    Dim dblmax As Double

    Set newrng = Worksheets("sheet3").Range("A1:A5, A8:A12")

    dblmax = Application.WorksheetFunction.Max(newrng)

    With Worksheets(2)
        .Range("D3").Value = dblmax
        .Range("E3").Value = newrng.Find(what:=dblmax, lookat:=xlWhole, LookIn:=xlValues).Address
    End With
End Sub