简体   繁体   中英

Excel VBA Can't access sheet on external workbook

I have created a custom function in Excel using VBA. I'm trying to get data from a different workbook using the Workbooks.Open(path) command. Here's my code:

Option Explicit

Function TestFunction() As String
  mySub
  TestFunction = "Success."
End Function


Sub mySub()

  Dim path As String
  Dim wk As Workbook

  path = "C:\Users\jg\Desktop\machine_data.xlsm"
  Set wk = Workbooks.Open(path)

  Dim ws As Worksheet
  Set ws = wk.Sheets(1)
  Debug.Print ws.Range("A2")
End Sub


Sub Test()
  Debug.Print (TestFunction())
End Sub

Now my problem is the following:

When I run the Sub Test() within the VBA environment from Excel everything works as planned. machine_data.xlsm gets opened and the field A2 shows up in debug.

Once I go to the workbook where I defined this module in and type =TestFunction() into a cell, I get a #VALUE! . The file also doesn't get opened.

If I comment these two lines:

  Set ws = wk.Sheets(1)
  Debug.Print ws.Range("A2")

the cell will show Success! , but the file still doesn't open.

What am I doing wrong? Both workbooks are .xlsm files. I am using Microsoft Office Excel 2007.

Just throw everything from mySub into the test function and if everything is successful have test function return the value of the cell. So testFunc = ws.Range("A2").

As DaveU already stated UDFs can only return values. I found a different workaround simply calling the function from within the VBA environment which lets me modify cell contents wherever I'd like.

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