首页 > 解决方案 > Excel VBA函数从一个范围内获取正值

问题描述

我有这个 Excel VBA 函数:

Function Positives(Rng As Range) As Range
  Dim cell As Range, out As Range

  For Each cell In Rng
    If cell > 0 Then
      If Not out Is Nothing Then
        Set out = Union(out, cell)
      Else
        Set out = cell
      End If
    End If
  Next cell
  Set Positives = out
End Function

当 Rng 范围内有非连续的正数时,为什么它不能很好地工作?例如,使用值 5、6、7、-3、4、5 但值 5、6、7、-3、-4、-5 它可以工作。

谢谢您的合作。

标签: excelvba

解决方案


excel使用数组函数显示不连续的范围值是有限制的,见下面的比较

具有连续范围:

在此处输入图像描述

当它不是连续范围时

在此处输入图像描述

在您的 VBA 代码中,当结果在连续范围内时,您将没有问题在数组公式中显示

在此处输入图像描述

当结果不是连续的范围时,它返回你提到的#Value,解决这个问题的方法之一是将结果更改为字符串显示,希望你觉得它有用:)

Function Positives1(Rng As Range) As String
Dim cell As Range, out As Range, outCell As Range
Dim result As String

For Each cell In Rng.Cells
    If cell.Value > 0 Then
      If Not out Is Nothing Then
        Set out = Union(out, cell)
      Else
        Set out = cell
      End If
    End If
Next cell
  
result = ""

For Each outCell In out.Cells
    If result <> "" Then
      result = result & "," & outCell.Value
    Else
      result = outCell.Value
    End If
Next

Positives1 = result
End Function

在此处输入图像描述


推荐阅读