Excel vba函数使用关闭工作簿中的变量获取值
我使用以下函数从关闭的工作簿中获取数据:Excel vba函数使用关闭工作簿中的变量获取值,excel,vba,Excel,Vba,我使用以下函数从关闭的工作簿中获取数据: Public Function GetValue(path, file, sheet, ref) ' Retrieves a value from a closed workbook Dim arg As String ' Make sure the file exists If Right(path, 1) <> "\" Then path = path & "\" If Dir(path &
Public Function GetValue(path, file, sheet, ref)
' Retrieves a value from a closed workbook
Dim arg As String
' Make sure the file exists
If Right(path, 1) <> "\" Then path = path & "\"
If Dir(path & file) = "" Then
GetValue = "File Not Found"
Exit Function
End If
' Create the argument
arg = "'" & path & "[" & file & "]" & sheet & "'!" & _
Range(ref).Range("A1").Address(, , xlR1C1)
' Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
但是,如果我在excel单元格中使用GetValue函数,提供与例程完全相同的所有4个参数,它总是抛出一个#值!错误
所以问题是,为什么它在例程中工作,而在作为函数调用时不工作?任何指点都将不胜感激。谢谢。经过几次尝试,我确实找到了3种解决方案:
Sub getDS()
asname = "data"
bsname = "Anual"
csname = "Total"
filename = Sheets("data").Range("B64").Value
path = Sheets("data").Range("B63").Value
Dim ws As Worksheet
Set ws = Sheets("data")
With ws.Range("D4:D34")
.ClearContents
.Formula = "='" & path & "[" & filename & "]" & bsname & "'!R11"
.Value = .Value
End With
With ws.Range("J4:J34")
.ClearContents
.Formula = "='" & path & "[" & filename & "]" & bsname & "'!U11"
.Value = .Value
End With
With ws.Range("J37:J37")
.ClearContents
.Formula = "='" & path & "[" & filename & "]" & csname & "'!DW96"
.Value = .Value
End With
End Sub
到目前为止,我发现这是最好、最快的VBA解决方案,可以在不打开已关闭工作簿(带变量)的情况下立即从工作簿中获取数据。经过几次尝试,我确实找到了3种解决方案:
Sub getDS()
asname = "data"
bsname = "Anual"
csname = "Total"
filename = Sheets("data").Range("B64").Value
path = Sheets("data").Range("B63").Value
Dim ws As Worksheet
Set ws = Sheets("data")
With ws.Range("D4:D34")
.ClearContents
.Formula = "='" & path & "[" & filename & "]" & bsname & "'!R11"
.Value = .Value
End With
With ws.Range("J4:J34")
.ClearContents
.Formula = "='" & path & "[" & filename & "]" & bsname & "'!U11"
.Value = .Value
End With
With ws.Range("J37:J37")
.ClearContents
.Formula = "='" & path & "[" & filename & "]" & csname & "'!DW96"
.Value = .Value
End With
End Sub
我发现这是迄今为止最好、最快的VBA解决方案,可以在瞬间从关闭的工作簿(带有变量)中获取数据,而无需打开它们。ExecuteExcel4Macro在UDFs中受保护。有关更多信息,请参阅。感谢您为我指明了正确的方向。我终于成功了。我会尽快把答案贴出来。再次感谢!ExecuteExcel4Macro在UDF中受保护。有关更多信息,请参阅。感谢您为我指明了正确的方向。我终于成功了。我会尽快把答案贴出来。再次感谢!