excel - 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 它可以工作。
谢谢您的合作。
解决方案
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
推荐阅读
- c++ - 使用指针反转数组
- vue.js - 在 VueJs 中处理大数据
- reactjs - JSX 元素类型“App”不是 JSX 元素的构造函数。“App”类型中缺少属性“上下文”
- java - java - 如何从现有的pdf中裁剪一部分并在java中创建一个新的pdf?
- laravel - 在 laravel 控制器中从空值创建默认对象
- android-studio - 同一库中不同版本的依赖项导致运行时崩溃
- google-apps-script - Google Apps 脚本:在脚本中触发文本文件下载
- ios - 通过 AWS 连接 winForm 和 mobile
- node.js - 当客户端是 android 应用程序时,将 https 添加到 aws ec2 服务器
- sql - SQL/VBA:如何从除一个月的第一天以外的一天开始按会计年度分组