简体   繁体   English

VBA-函数无法使用其他工作表中的输入

[英]VBA - Function doesn't work using inputs from other worksheets

I want to create a function in VBA that returns the variation between two prices within a user-specified interval. 我想在VBA中创建一个函数,该函数返回用户指定间隔内两个价格之间的差异。 For that I created the following function: 为此,我创建了以下功能:

Public Function ret(p, i)

    ret = (p / Cells((p.Row - i), p.Column)) - 1

End Function

Where the input 'p' represents the last observation of a vector of prices, and the input 'i' refers to the number of periods I want to move up in the price vector. 输入“ p”表示价格向量的最后观察值,输入“ i”是指我要在价格向量中向上移动的周期数。

The function works fine when I use inputs that are in the same worksheet where the function is defined. 当我使用定义该功能的同一工作表中的输入时,该功能可以正常工作。 However, when employ inputs from other worksheets the function returns '#VALUE!'. 但是,当使用其他工作表中的输入时,该函数将返回“ #VALUE!”。

What is the function missing to work "globally"? “全局”工作缺少的功能是什么?

Thanks!! 谢谢!!

Avoiding Cells : 避免Cells

Public Function ret(p, i)
    If p.Row > i Then
        ret = (p / p.Offset(- i, 0)) - 1
    Else
        ret = "???"
    End If
End Function

I would use 我会用

ret = (p / p.parent.Cells((p.Row - i), p.Column)) - 1

cells alone refers to the current sheet 仅单元格是指当前工作表

The proper place to put your UDF code is not inside a Worksheet_Module , these are usually for Worksheet related events, such as Worksheet_Change , etc. 放置UDF代码的适当位置不在Worksheet_Module ,这些位置通常用于与Worksheet相关的事件,例如Worksheet_Change等。

If you want to use a UDF from all worksheets, put it in a regular Module, so it's available to all worksheets. 如果要在所有工作表中使用UDF ,请将其放入常规模块中,以便所有工作表均可使用。

Also, you should define your UDF parameters properly, and not leave them empty. 另外,您应该正确定义UDF参数,不要将其留空。

In your case use the code below inside a regular Module: 您可以在常规模块中使用以下代码:

Public Function ret(p As Range, i As Long)

    ret = (p.Value / Cells(p.Row - 1, p.Column)) - 1

End Function

Screen-shot of VBAProject Explorer VBAProject Explorer的屏幕截图

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM