Excel从closures的文件中“拉”function,但对于范围而不是单个单元格

我正在使用http://numbermonger.com/2012/02/11/excel-pull-function-creating-dynamic-links-to-closed-workbooks/中的注释中的代码。 我把它粘贴在下面。 它已被修改,使其为我工作,所以一些variables可能有点多余。 无论如何,从服务器上closures的另一个工作簿获取值是非常有效的。 但我需要能够拉动范围。 我通过了ref1和ref2,并试图使它的工作方式,也试图通过作为一个variables的范围,如:

=SUM(MAGIC($B$9,"$C$22:$C$25")) 

但是那也行不通。 我刚刚得到一个“#VALUE!” 错误。 这里是我使用的代码,从上面的链接派生:

 Public xlapp As Object Private Function magic(ByVal filename As String, ref1 As String, ref2 As String) As Variant Dim arg As String Dim path As String Dim file As String Dim count As Integer Dim tempcount As Integer count = 0 While (Left(Right(filename, count), 1) <> "\") count = count + 1 Wend count = (count - 1) tempcount = Len(filename) tempcount = (tempcount - count) path = Left(filename, tempcount) count = (count - 1) file = Right(filename, count) count = 0 While (Left(Right(file, count), 1) <> "]") count = count + 1 Wend tempcount = 0 tempcount = Len(file) tempcount = tempcount - count file = Left(file, tempcount) If Dir(path & file) = "" Then magic = "File not found..." Exit Function End If If arg2 = "" Then arg = "'" & filename & "'!" & Range(ref1).Range("A1").Address(, , xlR1C1) Else arg = "'" & filename & "'!" & Range(ref1).Range("A1").Address(, , xlR1C1) & ":" & Range(ref2).Range("A1").Address(, , xlR1C1) End If magic = xlapp.ExecuteExcel4Macro(arg) End Function 

在我的工作簿中,我打开下面的代码,

 Private Sub Workbook_Open() Set xlapp = CreateObject("Excel.application") End Sub 

而且问题在于它可以很好地获得一个值:

 A1 = C:\users\sam\[test.xlsx]sheet1 B1 = magic(A1,"$H$7") -> returns the value from cell H7 in the other workbook 

但不是一个范围:

 A1 = C:\users\sam\[test.xlsx]sheet1 B1 = sum(magic(A1,"$H$7:$K$7") -> returns a VALUE error 

谢谢您的帮助!

这里:

 Public xlapp As Object Private Function magic(ByVal nameAndPath As String, ref1 As String, rowOffset As Integer, colOffset As Integer) As Variant thisFPend = InStrRev(nameAndPath, "\", Len(nameAndPath)) thisFP = Left(nameAndPath, thisFPend) thisFNend = InStrRev(nameAndPath, "]", Len(nameAndPath)) - 2 thisFN = Mid(nameAndPath, thisFPend + 2, thisFNend - thisFPend) If Dir(thisFP & thisFN) = "" Then magic = "File not found..." Exit Function End If 'Multiple values arg = "SUM('" & nameAndPath & "'!" & Range(ref1).Address(, , xlR1C1) & ":" & Range(ref1).Offset(rowOffset, colOffset).Address(, , xlR1C1) & ")" 'Single value ' arg = "SUM('" & nameAndPath & "'!" & Range(ref1).Address(, , xlR1C1) & ")" magic = xlapp.ExecuteExcel4Macro(arg) End Function 

我已经消除了find文件名和path的循环。 Instrrev是一个很棒的function!

这里的诀窍是,你不能像你要做的那样将多个范围值拉入单个单元格,你只能拉一个值。 所以我在参数中使用sum来传递给ExecuteExcel4Macro。

我没有在“ref1”中指定一个范围,而是包含了一个“rowOffset”参数,对于kick,还有一个“colOffset”参数。 所以,ref1是你想要求和的范围的开始,rowOffset是你想求和的行数。 因此,不要传递参数[“$ A $ 2:$ A $ 5”]来合计四行,而是传递[“$ A $ 2”,4]。