首页 > 解决方案 > 是否可以使用创建的函数从另一张表中获取特定数据?

问题描述

所以,我试图用这个概念创建一个 Excel 函数:根据用户输入的货币代码,搜索代码并从另一个工作簿的工作表中获取对应的汇率值。

例子:

User input in cell: =xrate(220) '220 being the code for dollar
Function returns: 5.000 'dollar exchange rate present in second workbook

我对在 VBA 中创建函数知之甚少,但尝试了以下方法:

Function xrate(code as Long)

Dim wb1 As Workbook, wb2 As Workbook
Dim ws1 as Worksheet, ws2 as Worksheet

Set wb1 = ThisWorkbook 'wb for the function
Set ws1 = wb1.Sheets(1)
Set wb2 = Workbooks.Open("C:\User\Test\rates.xlsm") 'wb with the rates
Set ws2 = wb2.Sheets("Rates")

ws2.Activate

'Column B is where the code is at and Column F has the correspondent Exchange Rate
For i = 1 to 156 '156 being the last row with data
    
        If ws2.Cells(i,"B").Value = code then

            xrate = Cells(i,"F").Value

        End if

Next i

End Function

我已经测试了与“Sub”相同的代码并且它工作正常,但作为一个函数它返回我#VALUE!错误,似乎什么也没做。

带有费率的表格不能与将使用该功能的工作簿位于同一工作簿中,因为该表格必须每天更新,并且用户总是让他们的工作簿被使用锁定。

有可能做这样的事情吗?

谢谢!

标签: excelvba

解决方案


推荐阅读