![](/img/trans.png)
[英]When called from an Excel VBA UDF, Range.Precedents returns the range and not its precedents. Is there a workaround?
[英]UDF in Excel VBA Editor only returns zero when a Double is wanted
此功能用於計算閉合導線的面積。 當作為子編寫並分配給特定單元格時,子工作完美。 但是,當用作函數時 - 如下所示 - 它僅返回零。 為什么? '功能設計用於容納任意數量的橫向側面
Public Function TraverseArea() As Double
Dim Area As Double
Area = 0
Range("N2").Select
Area = (ActiveCell.Value * (Range("M2").End(xlDown).Offset(-1, 0).Value - ActiveCell.Offset(1, -1).Value))
ActiveCell.Offset(1, 0).Select
While ActiveCell.Offset(1, -1) <> ""
Area = Area + (ActiveCell.Value * (ActiveCell.Offset(-1, -1).Value - ActiveCell.Offset(1, -1).Value))
ActiveCell.Offset(1, 0).Select
Wend
If Area < 0 Then
Area = Area * -1
End If
Area = Area / 2
TraverseArea = Area
End Function
我沒有您的數據或工作表結構,所以這一切都不在我的腦海中,但這應該讓您了解如何在沒有專門使用硬編碼范圍的情況下使用您的功能。
Sub TestFunction()
MsgBox TraverseArea(Range("N2"), Range("M2").End(xlDown).Offset(-1, -1))
End Sub
Public Function TraverseArea(MyRange As Range, MySecondRange As Range) As Double
Dim Area As Double, lr As Long, X as long
lr = Cells(Rows.Count, MyRange.Column).End(xlUp).Row
Area = (MyRange.Value * (MySecondRange.Value - MyRange.Offset(1, -1).Value))
For X = MyRange.Row To lr
If Cells(X, MyRange.Column - 1) = "" Then Exit For
Area = Area + (ActiveCell.Value * (ActiveCell.Offset(-1, -1).Value - ActiveCell.Offset(1, -1).Value))
Next
If Area < 0 Then Area = Area * -1
Area = Area / 2
TraverseArea = Area
End Function
這很可能需要一些調試,但應該足以讓你知道我在之前關於使用單元格引用而不選擇它們的評論中想說的內容。
代碼作為子過程工作,因為您可以看到正確的工作表,因為ActiveSheet屬性和subs允許您使用Range .Select方法和Range .Activate方法¹。 工作表上使用的函數需要知道它所處的工作表,並且選擇單元格不是批准的方法。
Public Function TraverseArea(Optional aRNG As Variant) As Double
Dim dAREA As Double, r As Long, rng As Range
dAREA = 0
With Application.Caller.Parent
If IsMissing(aRNG) Then Set aRNG = .Range("N2")
For Each rng In .Range(aRNG, aRNG.End(xlDown))
If IsEmpty(rng) Or Not IsNumeric(rng) Or Not CBool(Len(rng.Offset(1, -1))) Then _
Exit For
With rng
'Area = Area + (ActiveCell.Value * (ActiveCell.Offset(-1, -1).Value - ActiveCell.Offset(1, -1).Value))
dAREA = dAREA + .Value2 * (.Offset(0, -1).End(xlDown).Offset(-1, 0).Value2 - .Offset(1, -1).Value2)
End With
Next rng
End With
If dAREA < 0 Then
dAREA = dAREA * -1
End If
dAREA = dAREA / 2
TraverseArea = dAREA
End Function
Application.Caller有助於查找函數所在的父工作表。 沒有選擇或激活單元格,但通過提供行號,列號和Range.Offset屬性的一些操作,使用直接尋址循環它們。
¹ 請參閱如何避免在Excel VBA宏中使用選擇以獲取更多方法, 以避免依賴選擇和激活來實現目標。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.