我制作了一个可在单张纸上运行的 UDF。多张纸时会出现此问题。如果我在多张纸上有公式,并且如果我(重新)将其加载到一张纸上,它也会更改所有其他纸上的输出。
为什么会发生这种情况?我没有使用 ActiveWorksheet 或 Active Cell 或类似产品。
Function customreturn(security As Range, datacheck As Range) As Variant
Dim row_num As Integer
Dim row_num2 As Integer
Dim price1 As Double
Dim price2 As Double
Dim perfo As Double
Dim blank_end As Boolean
row_num = security.Row
col_num = security.Column
row_num2 = row_num + 1
col_num2 = datacheck.Column
If WorksheetFunction.IsError(datacheck.Value) = True Then
customreturn = "No data"
Else
price1 = Cells(row_num, col_num).Value
Do While WorksheetFunction.IsError(Cells(row_num2, col_num2).Value) = True
row_num2 = row_num2 + 1
Loop
price2 = Cells(row_num2, col_num).Value
perfo = price1 / price2 - 1
customreturn = perfo
End If
End Function
最佳答案
您使用Range.Cells property的三次都没有指定父工作表。因此父工作表默认为 ActiveSheet property 。这可以通过 With ... End With statement 来纠正。提供对范围参数之一 Range.Parent property 的工作表引用.
Function customreturn(security As Range, datacheck As Range) As Variant
Dim row_num As Long, row_num2 As Long, col_num As Long, col_num2 As Long
Dim price1 As Double, price2 As Double, perfo As Double
Dim blank_end As Boolean
row_num = security.Row
col_num = security.Column
row_num2 = row_num + 1
col_num2 = datacheck.Column
With security.Parent
If IsError(datacheck) Then
customreturn = "No data"
Else
price1 = .Cells(row_num, col_num).Value
Do While IsError(.Cells(row_num2, col_num2))
row_num2 = row_num2 + 1
Loop
price2 = .Cells(row_num2, col_num).Value
perfo = price1 / price2 - 1
customreturn = perfo
End If
End With
End Function
在 With ... End With 中,所有 Cells
均以 .Cells
形式引用,以表明父工作表是 With 中引用的工作表。 .. 结束于。
您不必显式比较工作表的 ISERROR 或 VBA 的 IsError function为真。它已经知道它是 True 还是 False。
有人指出(感谢 BruceWayne )您有两个未声明的变量,col_num 和 col_num2。可以通过添加 Option Explicit 来避免这种情况。 ¹ 到声明区域中每个代码表的顶部。
<小时/>1 在 VBE 的工具 ► 选项 ► 编辑器属性页中设置 需要变量声明 将放置 Option Explicit每个新创建的代码表顶部的 语句。这将避免愚蠢的编码错误,例如拼写错误,以及影响您在变量声明中使用正确的变量类型。无需声明而动态创建的变量都是变体/对象类型。使用Option Explicit被广泛认为是“最佳实践”。
关于VBA UDF 更改所有工作表上的值。怎么限制为1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35365248/