【问题标题】:How to turn this Macro Based function into a genuine VBA function?如何把这个基于宏的函数变成真正的 VBA 函数?
【发布时间】:2013-10-29 05:09:28
【问题描述】:

我正在尝试编写一个 VBA 函数,以便我可以访问已关闭的 Excel 工作簿的单元格值。我在网上发现可以写一个这样的宏例程:

Public Sub TestGetValue()

    p = "C:\Users\Jake\Desktop"
    f = "TestSample.xlsx"
    s = "Sheet1"
    a = "B10"

    Call GetValue(p, f, s, a)
    x = GetValue(p, f, s, a)
    MsgBox x 
  
End Sub

Public Function GetValue(path, file, sheet, ref)
'   Retrieves a value from a closed workbook
    Dim arg As String
'   Make sure the file exists
    If Right(path, 1) <> "\" Then path = path & "\"
    If Dir(path & file) = "" Then
        GetValue = "File Not Found"
        Exit Function
    End If
'   Create the argument
    arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
    range(ref).range("A1").Address(, , xlR1C1)
'   Execute an XLM macro
    GetValue = ExecuteExcel4Macro(arg)
End Function

我可以将TestGetValue() 作为宏运行,但是当我尝试在 Excel 单元格中直接使用GetValue() 作为自定义 VBA 函数时,它不起作用。 GetValue = ExecuteExcel4Macro(arg)这行好像不能执行。

有谁知道如何解决这个问题?我正在使用 Excel 2010。

【问题讨论】:

  • this
  • 还有this 所以回答
  • 谢谢,但仍然......我知道如何编写一个可以打开工作簿和更新数据的宏,但我不知道如何编写可以从 Excel 单元格调用的 VBA 函数。例如,如果您编写这样的函数:code Function OpenWorkbookToPullData(path, cell) Dim openWb As Workbook Set openWb = Workbooks.Open(path) Dim openWs As Worksheet Set openWs = openWb.Sheets("Sheet1") OpenWorkbookToPullData = openWs.Range(cell) openWb.Close (False) End Function code 你不能从 Excel 单元格调用这个函数,虽然你可以从宏调用它。
  • 这超出了函数的范围。函数可以返回值,但无法像您希望的那样作用于环境。即使你能做到这一点,我也不认为这将是一个好的选择,因为会发生大量的资源计算。根据需要编写代码以将值转储到单元格中可能会更好。

标签: excel vba excel-4.0


【解决方案1】:

据我所知,函数ExecuteExcel4Macro 没有定义。但可能还有更简单的方法。 尝试打开包含所需值的工作簿。例如

Dim tempWb As Workbook
Dim testValue

Set tempWb = Application.Workbooks.Open(path)
testValue = tempWb.Sheets(1).Cells(1,1)

路径可以像你的例子一样传递。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    相关资源
    最近更新 更多