2012-01-23 103 views
0

一个函数中我在Excel 2007中两个工作簿,A和B.访问表在VBA在Excel

在AI有一个需要得到工作簿B.我觉得一定值的函数没有办法给一个函数内做到这一点(正常子内是没有问题的,但我需要一个功能 - 这实际上是比刚刚起步的电池(1,1)更复杂)的一个

function getDataFromB(sheetName,row,col) 
    x = Application.run ("E:\B.xlsm!getData",sheetName,row,col) 
    getDataFromB = x 
end getDataFromB 

In B

function getData(sheetName,row,col) 
    x=sheets(sheetName).cells(row,col) 
    getData = x 
end getData 

当的getData B内部被称为它看起来SHEETNAME在工作簿中 - 而不是B.和写作

x = workbooks("E:\B.xlsm").sheets(sheetName).cells(row,col) 

不起作用

我将如何解决这个问题?

回答

1

疲倦和测试

变化

功能getDataFromB(SHEETNAME,行,列)
X = Application.run( “E:\ B.xlsm的getData”,SHEETNAME,行,列)
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 

您需要添加“端功能”,因为我在上面所做的。

+0

谢谢,但这并不能解决文件B中调用getData仍然访问文件A中的表单的问题,因为它从第一个地方从文件A调用....(最终函数是拼写错误在我的部分,感谢您指出了这一点!) – user387184

+0

不,它不:)。我在发布之前测试了代码。它引用文件B中的表单。如何使用函数“getDataFromB”? –

+0

谢谢,最后它的工作... – user387184