我正在使用http://numbermonger.com/2012/02/11/excel-pull-function-creating-dynamic-links-to-closed-workbooks/中的评论中的代码。我把它贴在下面。它已被修改以使其适用于我,因此一些变量可能有点多余。无论如何,从服务器上关闭的另一个工作簿中提取值非常有用。但我需要能够拉动范围。我传入ref1和ref2并试图让它以这种方式工作,并试图将范围作为一个变量传递,如:
=SUM(MAGIC($B$9,"$C$22:$C$25"))
但那也没有用。我只是得到了#34; #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
感谢您的协助!
答案 0 :(得分:0)
下面:
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
我已经删除了查找文件名和循环的循环。路径。 Instrrev是一个很棒的功能!
这里的诀窍在于,您无法将多个范围值拉入单个单元格中,就像您尝试这样做一样,您只能提取单个值。所以我在参数中使用了sum来传递给ExecuteExcel4Macro。
而不是在&#34; ref1&#34;中指定范围。我已经包含了一个&#34; rowOffset&#34;争论,并且,对于踢,一个&#34; colOffset&#34;论点。因此,ref1是要求求和的范围的起点,rowOffset是要求求和的行数。因此,不要将参数[&#34; $ A $ 2:$ A $ 5&#34;]传递给四行,而是传递[&#34; $ A $ 2&#34;,4]。