我在Excel 2007中有两个工作簿,A和B.
在AI中有一个需要从工作簿B中获取某些值的函数。我发现在函数中没有办法做到这一点(在普通子函数内没有问题,但我需要一个函数 - 实际上它比复杂更复杂得到单元格(1,1))
在A:
function getDataFromB(sheetName,row,col)
x = Application.run ("E:\B.xlsm!getData",sheetName,row,col)
getDataFromB = x
end getDataFromB
在B
function getData(sheetName,row,col)
x=sheets(sheetName).cells(row,col)
getData = x
end getData
每当调用B中的getData时,它会在工作簿A中查找sheetName - 而不是B.并编写
x = workbooks("E:\B.xlsm").sheets(sheetName).cells(row,col)
不起作用
我该如何解决这个问题?
答案 0 :(得分:1)
TIRED AND TESTED
更改
function getDataFromB(sheetName,row,col)
x = Application.run(“E:\ B.xlsm!getData”,sheetName,row,col)
getDataFromB = x 结束getDataFromB
到
Function getDataFromB(sheetName, row, col)
Dim FilePath As String, FileName As String
Dim wbTarget As Workbook
Dim x As Variant
Dim CloseIt As Boolean
'~~> Set file name and path here.
FileName = "B.xlsm"
FilePath = "E:\"
On Error Resume Next
Set wbTarget = Workbooks(FileName)
If Err.Number <> 0 Then
'~~> Open the workbook
Err.Clear
Set wbTarget = Workbooks.Open(FilePath & "\" & FileName)
CloseIt = True
End If
'~~> Check and make sure workbook was opened
If Err.Number = 1004 Then
MsgBox "File does not exist!"
Exit Function
End If
On Error GoTo 0
x = Application.Run(wbTarget.Name & "!getData", sheetName, row, col)
getDataFromB = x
If CloseIt = True Then
'~~> If the target workbook was opened by the macro, close it
wbTarget.Close savechanges:=False
Else
'~~> If the target workbook was already open, reactivate this workbook
ThisWorkbook.Activate
End If
End Function
同样在文件B中将代码更改为
Function getData(sheetName,row,col)
x=sheets(sheetName).cells(row,col)
getData = x
End Function
您需要像我上面所做的那样添加“结束功能”。