首页 > 解决方案 > 通过超链接公式调用另一个 XLAM 中的函数 - Excel VBA

问题描述

我正在尝试使用此答案,但将其设置在另一个 xlam 工作簿中的函数位置。

例子:

这适用于远程工作簿:

Sub Test()
  FuncName = "#MyFunctionkClick()"
  MyVal = "TestVal"
  Range("A1").Value = MyVal
  Range("A1").Formula = "=HYPERLINK(""" & FuncName & """, """ & Range("A1").Value & """)"
End Sub
Sub TestTwo()
 Application.Run ("'remotewb.xlam'!MyFunctionkClick")
End Sub
Function MyFunctionkClick()
 Set MyFunctionkClick = Selection 'This is required for the link to work properly
 MsgBox "The clicked cell addres is " & Selection.Row
End Function

但我没有运气就试过了:

Sub Test()
'Application.Run ("'Master Calc with Macro.xlsm'!SummarizeMaster")
'Application.Run ("'remotewb.xlam'!testremote")
'Application.Run ("'remotewb.xlam'!#MyFunctionkClick()")
'Application.Run ("'remotewb.xlam'!MyFunctionkClick") ' When calling from Remote WB it errored if I used ()
 'Range("A1:A5").Formula = "=HYPERLINK(""#MyFunctionkClick()"", ""Run a function..."")"
 ' Range("A1:A5").Formula = "=HYPERLINK(""#MyFunctionkClick()"", ""Run a function..."")"
 Range("A1:A5").Formula = "=HYPERLINK(""[remotewb.xlam]!MyFunctionkClick"", ""Run a function..."")"
 'Range("A1").Formula = "=HYPERLINK(""Application.Run (" 'remotewb.xlam'!MyFunctionkClick")"", ""Run a function..."")"
End Sub

标签: excelvbahyperlinkformula

解决方案


请尝试下一个场景:

  1. 在另一个工作簿中创建一个函数。出于测试原因,最好将其放在“Personal.xlsb”中,因为我正在尝试:
Function GiveMeFive(x As Long, y As Long) As Long
    Debug.Print "In Personal.xlsb code: " & x + y 'not important, ONLY TO SEE IT WORKING with parameters in Immediate Window
    GiveMeFive = 5 'it can be calculated, but look to the function name :)
End Function
  1. 在活动工作表中创建(必要的)超链接(可以在任何工作表中创建):
Sub TestCalFunctionHyp()
  Dim FuncName As String, myVal As String
  FuncName = "#MyFunctionHyp()"
  myVal = "Call external Function (parameters):4|3" 'just to see how to call it with parameters
  Range("A1").Value = myVal
  Range("A1").Formula = "=HYPERLINK(""" & FuncName & """, """ & Range("A1").Value & """)"
End Sub
  1. (直接)调用(通过超链接)函数的外观:
Function MyFunctionHyp()
Dim arr
 Set MyFunctionHyp = Selection
 arr = Split(Split(Selection.Value, ":")(1), "|")
 TestTwo CLng(arr(0)), CLng(arr(1)) 'calling the sub calling the one in the other wb
End Function
  1. 在另一个工作簿中调用该函数的子应如下所示:
Sub TestTwo(arg1 As Long, arg2 As Long)
 Dim x As Long
 x = Run("'C:\Users\YourUser\AppData\Roaming\Microsoft\Excel\XLSTART\PERSONAL.XLSB'!GiveMeFive", arg1, arg2)
   Debug.Print "Received from called function: " & x
End Sub

该函数使用其完整路径调用该函数,只是因为如果保存该函数的工作簿未打开,它将打开它......

请注意调整路径以使用您的真实YourUser...

我想在测试后收到一些反馈。如果有些事情不够清楚,请不要犹豫,要求澄清。


推荐阅读