如何从Excel工作簿中选取值并在活动工作簿上按function返回

我的目标是实现一些function,我给他们参数的电动机的功率,频率和速度,并看看另一个工作簿(我有电机数据),并返回大小,轴直径和其他电机细节。

由于我还没有掌握很多的VBA,我试图实现一个函数,只是转到另一个工作簿中的单元格,并返回值:

Function Test() As String Dim name As String With Workbooks.Open("D:\ExcelTest\WbSource.xlsm").Sheets("Sheet1") name = .Cells(2, 3) End With Test= name ActiveWorkbook.Save ActiveWorkbook.Close End Function 

问题是它给了我一个#VALUE! 错误,但每个使用的variables被定义为一个string和单元格具有通用格式(如果我将单元格格式更改为文本,它给了我相同的消息)。

尽我所能,我不能让workbooks.open工作在一个函数,即使该函数调用一个子。 您可以打开工作簿打开事件中的目录文件,然后在closures事件之前再次closures它。

在VProject资源pipe理器中,右键单击“ThisWorkBook”和“查看代码”。
在顶部的select列表中,select“工作簿”,并创build子Workbook_open()过程。 如果没有,请在右侧select列表中select“打开”。 放入以下内容:

 Application.Workbooks.Open ("D:\ExcelTest\WbSource.xlsm") ThisWorkbook.Activate 'restores the "focus" to your worksheet 

然后点击右边的select列表并select“beforeClose”并放入

 On Error Resume Next 'this keeps it from crashing if the catalogue is closed first Workbooks("WbSource.xlsm").Close 

只要工作表首先打开wbsource文件,该函数将工作。

这里有一个在队列中调度UDF执行的方法,在UDF之外处理可以摆脱UDF限制。 所以来自已closures的工作簿的值通过一个链接通过ExecuteExcel4Macro()获得。

将下面的代码放入其中一个VBAProject模块中:

 Public Queue, QueueingAllowed, UDFRetValue Function UDF(ParamArray Args()) If IsEmpty(Queue) Then Set Queue = CreateObject("Scripting.Dictionary") UDFRetValue = "" QueueingAllowed = True End If If QueueingAllowed Then Queue.Add Application.Caller, (Args) UDF = UDFRetValue End Function Function Process(Args) If UBound(Args) <> 4 Then Process = "Wrong args number" Else ' Args(0) - path to the workbook ' Args(1) - filename ' Args(2) - sheetname ' Args(3) - row ' Args(4) - column On Error Resume Next Process = ExecuteExcel4Macro("'" & Args(0) & "[" & Args(1) & "]" & Args(2) & "'!R" & Args(3) & "C" & Args(4)) End If End Function 

将下面的代码放入VBAProject Excel对象的ThisWorkbook部分:

 Private Sub Workbook_SheetCalculate(ByVal Sh As Object) Dim Item, TempFormula If Not IsEmpty(Queue) Then Application.EnableEvents = False QueueingAllowed = False For Each Item In Queue TempFormula = Item.FormulaR1C1 UDFRetValue = Process(Queue(Item)) Item.FormulaR1C1 = TempFormula Queue.Remove Item Next Application.EnableEvents = True UDFRetValue = "" QueueingAllowed = True End If End Sub 

之后,您可以使用UDF通过工作表公式获取封闭工作簿中的值:

 =UDF("D:\ExcelTest\";"WbSource.xlsm";"Sheet1";2;3) 

无论如何,您可以将Workbooks.Open()或其他任何东西添加到Function Process(Args) ,使其以您想要的方式工作。 上面的代码只是一个例子。 我在这里和这里回答了类似的问题,以便描述可能会有所帮助。

我build议:

  1. 通过手动或通过UDF 之外的VBA打开WbSource.xlsm。
  2. 将parameter passing给UDF
  3. 让UDFsearch新打开的工作簿的列以find正确的logging
  4. 让UDF将行号传回给工作表
  5. 在工作表中使用Match()/ Index()公式来检索其他数据。