簡體   English   中英

如何從Excel工作簿中選取值並按功能將其返回給活動工作簿

[英]How can I pick values from an Excel workbook and return them by function on active workbook

我的目標是實現一些功能,向它們提供電動機的功率,頻率和速度參數,並查看另一本工作簿(在其中有電動機數據)並返回尺寸,軸直徑和其他電動機詳細信息。

由於我對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! 錯誤,但使用的每個變量都定義為字符串,並且單元格具有常規格式(如果我將單元格格式更改為文本,則會給我相同的消息)。

盡我所能,即使該函數調用了子函數,也無法使workbooks.open在函數中工作。 您可以在工作簿打開事件中打開目錄文件,然后在關閉之前事件中再次將其關閉。

在VProject Explorer中,右鍵單擊“ ThisWorkBook”和“查看代碼”。
在頂部的選擇列表中,選擇“工作簿”,然后應創建子Workbook_open()過程。 如果沒有,請在右側選擇列表中選擇“打開”。 輸入以下內容:

Application.Workbooks.Open ("D:\ExcelTest\WbSource.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 Objects的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) ,以使其按您想要的方式工作。 上面的代碼僅是示例。 我已經在這里這里回答了類似的問題,因此描述可能會有所幫助。

我建議:

  1. 手動或通過UDF 外部的VBA打開WbSource.xlsm。
  2. 將參數傳遞給UDF
  3. 讓UDF搜索新打開的工作簿的列以查找正確的記錄
  4. 讓UDF將行號傳回工作表
  5. 在工作表中,使用Match()/ Index()公式檢​​索其他數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM