VBA UDF更改所有工作表上的值。 如何限制到一个?

我做了一个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属性的三次中的任何一次指定父工作表,所以父工作表默认为ActiveSheet属性 。 这可以用一个With … End With语句纠正,该语句提供了对Range.Parent属性之一的范围参数的工作表引用。

 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 … End With中引用的Cells

您不必显式比较工作表的ISERROR或VBA的IsError函数为True 。 它已经知道它是真是假。

有人指出(感谢BruceWayne )你有两个未声明的variablescol_num和col_num2。 这可以通过在声明区域的每个代码表的顶部添加Option Explicit 1来避免。


¹ 在VBE工具中设置需要variables声明 ►选项►编辑器属性页面将把Option Explicit语句放在每个新创build的代码表的顶部。 这将避免像拼写错误这样的愚蠢的编码错误,也会影响你在variables声明中使用正确的variablestypes。 在没有声明的情况下即时创build的variables都是变体/对象types。 使用Option Explicit被广泛认为是“最佳实践”。