简体   繁体   中英

How do I open an existing workbook in VBA?

I would like to use my function in new workbook, the function is using datas from an old Workbook, where was written.

My function in new workbook is working correctly only, if the old workbook is open too. Otherwise result is #Value.

My code is:

Function findfix(EAN,year, As Variant)

Set wb = Workbooks.Open("H:\dokumenty\NPU\NPUfix.xlsm")
ThisWorkbook.Activate

rowPos = findEAN(EAN)

c = Workbooks("NPUfix").Sheets("EAN").Cells(rowPos, 18).Value
.
.
.

Simply copy the function and related code into a new module, in the new workbook

Then just change ("H:\\dokumenty\\NPU\\NPUfix.xlsm") to your new location.

Private 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

Then to get the value required

Sub TestGetValue()
    p = "c:\XLFiles\Budget"
    f = "Budget.xls"
    s = "Sheet1"
    a = "A1"
    MsgBox GetValue(p, f, s, a)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM