gpt4 book ai didi

function - 在VBA中的数组中找到最小正值(大于0)

转载 作者:行者123 更新时间:2023-12-04 21:17:17 24 4
gpt4 key购买 nike

我有一个具有以下值的数组(AlphaVector):

-0.2
-0.7
0
0.4
0.3
0.1

我想从上面的数组中选择正值并将其放在另一个名为 Alpha 的数组中,以便我可以从 Alpha 中选择最小的正值。我的目标是从上面的数组中获取值 0.1。
这是我到目前为止的代码。 Alpha 填充正常,因为 Msgbox 指示正确的值,但我得到的返回值是 0 而不是 0.1。
Function FindMin(AlphaVector)
Dim iCount As Long
Dim N As Integer, i As Integer
N = AlphaVector.Cells.Count
Dim Alpha() As Double
ReDim Alpha(N) As Double
For i = 1 To N
If AlphaVector(i) > 0 Then
Alpha(i) = AlphaVector(i)
Else
Alpha(i) = 100000000000#
End If
MsgBox ("Alpha(i)= " & Alpha(i))
MsgBox ("AlphaVector(i)= " & AlphaVector(i))
Next i
FindMin = WorksheetFunction.Min(Alpha)
End Function

你能告诉我如何解决吗?另外,如果有更高效的写法,也许不介绍Alpha,请告诉我。谢谢。

最佳答案

您对数组 Alpha 使用了错误的索引.它是从零开始的,因为您使用 i 填充它,从1开始,你离开Alpha(0)为默认值,即 0。
WorksheetFunction.Min(Alpha)返回最小值,您现在知道它始终为 0。:-)

你需要重新设计你的函数来处理这个问题。很快就会有例子。

编辑 - 代码示例 - 更新为 UDF

我在看到您的评论之前完成了这个示例,所以在我的代码中 AlphaVector是一个数组。无论如何,最好显式声明任何变量并避免 Variant如果可以,请键入,如果您不声明变量,则使用该类型。这就是我使用 Option Explicit 的原因.你也应该。 :-)

可能有很多方法可以做你想做的事,但这是其中之一:

Option Explicit

Function FindMin(AlphaVector)
Dim iNew As Integer, i As Integer
Dim iCount As Integer
Dim Alpha() As Variant

iCount = AlphaVector.Cells.Count

'***** Use size of AlphaVector
ReDim Alpha(0 To iCount - 1)
iNew = 0

For i = 1 To iCount
'***** Only save values greater than 0
If AlphaVector(i) > 0 Then
Alpha(iNew) = AlphaVector(i)
'***** Keep track of how many values you save
iNew = iNew + 1
End If
Next i

'***** Remove any empty items in the Alpha array
ReDim Preserve Alpha(0 To iNew - 1)

'***** Reture result of the Min function
FindMin = WorksheetFunction.Min(Alpha)
End Function

关于function - 在VBA中的数组中找到最小正值(大于0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13383208/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com