如何在VBA中打开现有工作簿?

时间:2019-02-28 14:16:47

标签: excel vba

我想在新工作簿中使用我的函数,该函数使用的是旧工作簿中的数据,写在哪里。

如果旧工作簿也已打开,则我在新工作簿中的功能只能正常工作。否则结果为#Value。

我的代码是:

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
.
.
.

1 个答案:

答案 0 :(得分:0)

只需将功能和相关代码复制到新工作簿中的新模块中

然后只需将("H:\dokumenty\NPU\NPUfix.xlsm")更改为您的新位置。

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

然后获取所需的值

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