如何将此基于宏的函数转换为真正的VBA函数?
我正在尝试编写VBA函数,以便可以访问已关闭Excel工作簿的单元格值。我在网上发现可以编写如下宏例程:如何将此基于宏的函数转换为真正的VBA函数?,vba,excel,Vba,Excel,我正在尝试编写VBA函数,以便可以访问已关闭Excel工作簿的单元格值。我在网上发现可以编写如下宏例程: Public Sub TestGetValue() p = "C:\Users\Jake\Desktop" f = "TestSample.xlsx" s = "Sheet1" a = "B10" Call GetValue(p, f, s, a) x = GetValue(p, f, s, a) MsgBox x End Su
Public Sub TestGetValue()
p = "C:\Users\Jake\Desktop"
f = "TestSample.xlsx"
s = "Sheet1"
a = "B10"
Call GetValue(p, f, s, a)
x = GetValue(p, f, s, a)
MsgBox x
End Sub
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 2010 在我看来,函数ExecuteExcel4Macro没有定义。但可能还有更简单的方法。 尝试打开包含desierd值的工作簿。例如
tempWb as workbook
dim testValue
set tempWb = application.workbooks.open(path)
testValue = tempWb.sheets(1).cells(1,1)
路径可以按照您的示例进行传递。另请参见SO应答谢谢,但仍然。。我知道如何编写可以打开工作簿和更新数据的宏,但我不知道如何编写可以从Excel单元格调用的VBA函数。例如,如果编写这样的函数:
code
function OpenWorkbookToPullData(路径,单元格)Dim openWb As Workbook Set openWb=Workbooks.Open(路径)Dim openWs As worket openWs=openWb.Sheets(“Sheet1”)OpenWorkbookToPullData=openWs.Range(单元格)openWb.Close(False)End Functioncode
您不能从Excel单元格调用此函数,尽管您可以从宏调用它。这超出了函数的范围。函数可以返回值,但不能像您希望的那样对环境进行操作。即使您可以这样做,我也不认为这是一个好的选择,因为可能会发生资源密集型计算。如果需要,最好编写代码将值转储到单元格中。
tempWb as workbook
dim testValue
set tempWb = application.workbooks.open(path)
testValue = tempWb.sheets(1).cells(1,1)