VBA函数仅适用于一个工作表

时间:2016-01-08 19:15:45

标签: excel vba excel-vba

我有一个带一个参数的函数。该函数的目标是在"数据"中寻找匹配(对输入的参数)。列B列然后返回F列中的相应单元格(使用某些因子I' m)。我希望此功能能够在所有工作表上工作。不幸的是,它似乎只适用于数据表。例如,如果我键入" = CPOST(B18)"在分析仪表格的随机单元格中,我得到一个" #Value!"错误。

我用谷歌搜索了这个搜索结果并且仍未找到任何内容。这是我第一次在这个网站上提出问题,尽管已经从这里得到了大量答案。谢谢大家。

以下是代码:

Public Function CPost(rng As Range)

' find the date in the data sheet from column 2 (B)
' sum the prior 21 abs values from column 6 (F)
' take the sum * factor * 100
' return that total as output

Dim LR As Integer

Set sh1 = Sheets("Analyzer")
Set sh2 = Sheets("Data")
Set sh3 = Sheets("Notes")

LR = sh2.Cells(Rows.Count, 1).End(xlUp).Row

For x = 3 To LR
    y = Cells(x, 2).Value
    If y = rng Then
        Set xx = Cells(x + 1, 6).Resize(21, 1)
        yy = Application.WorksheetFunction.Average(xx)
        zz = yy * 5 * 100
        CPost = zz
    End If
Next x

End Function

更新:

根据以下所有回复,我非常感谢,我已将我的代码从Module4复制到ThisWorkbook。我删除了Module4(ht Dirk)。我将工作表限定符添加到我的范围(ht BruceTimScott)。我现在正在获得#34; #NAME?"我尝试在工作簿中的任何工作表中键入公式时出错。这是新代码。如果我错过了一些明显的东西,我很抱歉:

Public Function CPost(rng As Range)

' find the date in the data sheet from column 2 (B)
' sum the prior 21 abs values from column 6 (F)
' take the sum * factor * 100
' return that total as output

With Sheets("Data")

Dim LR As Integer

LR = Worksheets("Data").Cells(Rows.Count, 1).End(xlUp).Row

For x = 3 To LR
    y = Worksheets("Data").Cells(x, 2).Value
    If y = rng Then
        Set xx = Worksheets("Data").Cells(x + 1, 6).Resize(21, 1)
        yy = .Application.WorksheetFunction.Average(xx)
        zz = yy * 5 * 100
        CPost = zz
    End If
Next x

End With

End Function

1 个答案:

答案 0 :(得分:0)

尝试在函数定义中更改Public Function CPost(rng As Range) Public Function CPost(rng As Excel.Range)