我的目标是实施一些功能,在其中我给它们提供电动机的功率,频率和速度参数,然后查看另一个工作簿(我拥有电动机数据)并返回尺寸,轴直径和其他电动机细节。
由于我没有掌握太多VBA,因此我尝试实现一个功能,该函数只能输入另一个工作簿中的单元格并返回值:
Function Test() As String
Dim name As String
With Workbooks.Open("D:ExcelTestWbSource.xlsm").Sheets("Sheet1")
name = .Cells(2, 3)
End With
Test= name
ActiveWorkbook.Save
ActiveWorkbook.Close
End Function
问题在于它给了我#VALUE!
错误,但是使用的每个变量都定义为字符串,并且单元格具有通用格式(如果我将单元格式更改为文本,则为我提供相同的消息)。
尝试尽可能地,即使函数调用sub,我也无法获得工作簿。您可以在工作簿公开活动中打开目录文件,然后在关闭事件之前再次关闭它。
在vproject Explorer中,右键单击" thisworkbook"one_answers"查看代码"。
在顶部的选择列表中,应该创建Select Workbook和Sub Workbook_open()过程。如果不是,请在正确的选择列表中选择"打开"。输入以下内容:
Application.Workbooks.Open ("D:ExcelTestWbSource.xlsm")
ThisWorkbook.Activate 'restores the "focus" to your worksheet
然后单击右选择列表,然后选择" beforeclose",然后放入
中On Error Resume Next 'this keeps it from crashing if the catalogue is closed first
Workbooks("WbSource.xlsm").Close
只要工作表首先打开WBSource文件,该函数就可以工作。
这是一种在队列中安排UDF执行的方法,并在UDF之外处理可以摆脱UDF限制。因此,封闭的工作簿的值通过链接通过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对象的此Workbook部分:
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)
中,以使其按照所需的方式工作。上面的代码只是一个示例。我在这里和这里回答了类似的问题,因此描述可能会有所帮助。
我建议:
- 手动或通过vba 外部打开wbsource.xlsm
- 将参数传递到UDF
- 让UDF搜索新打开的工作簿的列以找到正确的记录
- 让UDF通过行号返回工作表
- 在工作表中,使用 match()/index()公式来检索其他数据。