【问题标题】:How to implement Application.Caller in Public Function如何在公共函数中实现 Application.Caller
【发布时间】:2018-05-21 06:46:33
【问题描述】:

下面的函数取 F 列(货币代码)中的值,并在 H 列返回函数输出(相当于输入的 20 美元)。

问题是当我将方程向下拖动到 H 列(从 H2 开始)时,方程没有更新 F 列中的值。

示例:H2 = Oanda(F2)
当我把它往下拉(比如 F10)时,无论 F3-F10 的值是多少,等式都会给我 Oanda(F2) 的输出。我需要一些帮助来实现 Application.Caller 功能。

Option Explicit

Public Function Oanda(ConvertWhat As String)

'References
'   Microsoft XML, vs.0
'   Microsoft Internet Controls
'   Microsoft HTML Object Library

Dim Conversion As String
Conversion = ThisWorkbook.Sheets("Employee").Range("F" & ActiveCell.Row).Value2

Dim IE As New InternetExplorer
'IE.Visible = True
IE.Navigate "https://www.oanda.com/currency/converter?quote_currency=USD&base_currency=" & Conversion

Do
    DoEvents
Loop Until IE.ReadyState = ReadyState_Complete
Dim Doc As HTMLDocument
Set Doc = IE.Document
Dim Ans As String
Ans = Trim(Doc.getElementsByTagName("tbody")(2).innerText)
Dim AnsExtract As Variant
AnsExtract = Split(Ans, " ")

Oanda = AnsExtract(4) * 20

End Function

【问题讨论】:

  • 输出不是问题。问题是该函数无法识别从哪个单元格调用该函数,因此在拖动(或复制和粘贴)时返回相同的值。它仅在手动输入方程式时识别呼叫单元。
  • 如果 F2=EUR 则 L2=16.99。如果 F3=USD,则 L3=20。如果我在 L2 中键入函数,然后向下拖动到 L3,我得到两个单元格的 16.99。

标签: excel vba internet-explorer web-scraping automation


【解决方案1】:

使用传递给函数的变量

Option Explicit

Public Function Oanda(ByVal ConvertWhat As String) As Double

    'References
    '   Microsoft XML, vs.0
    '   Microsoft Internet Controls
    '   Microsoft HTML Object Library
    Dim IE As New InternetExplorer
    'IE.Visible = True
    IE.Navigate "https://www.oanda.com/currency/converter?quote_currency=USD&base_currency=" & ConvertWhat

    Do
        DoEvents
    Loop Until IE.ReadyState = ReadyState_Complete
    Dim Doc As HTMLDocument
    Set Doc = IE.Document
    Dim Ans As String
    Ans = Trim$(Doc.getElementsByTagName("tbody")(2).innerText)
    Dim AnsExtract As Variant
    AnsExtract = Split(Ans, " ")

    Oanda = AnsExtract(4) * 20

End Function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-06
    相关资源
    最近更新 更多