首先,我在这里做的是逻辑吗? 其次,我的单引号开始出现文件路径时出现错误。
stuff = Workbooks('\\public\Documents\Amazon Retail\Analysis\[US Retail Quick Reference.xlsx]').Sheets("Quick Reference").Range("A1")
答案 0 :(得分:1)
假设您有一个Excel实例,并且没有使用多个Excel实例:
如果该文件已经打开,则必须仅通过其名称引用它,而不是完整路径。如果文件尚未打开,则需要先打开它(然后仅按名称引用它)。
改变这个:
stuff = Workbooks('\\public\Documents\Amazon Retail\Analysis\[US Retail Quick Reference.xlsx]').Sheets("Quick Reference").Range("A1")
To This:
stuff = Workbooks("US Retail Quick Reference.xlsx").Sheets("Quick Reference").Range("A1")
确保将stuff
声明为String
或可能为Variant
类型(如果A1可能包含非文本或错误值)。
如果您在运行时不知道该文件是打开还是打开,那么您可以将代码归类为:
Function IsWorkbookOpen(path as String, name as String) As Boolean
Dim wb as Workbook
On Error Resume Next
Set wb = Workbooks(name)
If wb.FullName = path & name Then
IsWorkbookOpen = True
End If
End Function
然后喜欢:
Dim path as String, fileName as String
path = "\\public\Documents\Amazon Retail\Analysis\"
fileName = "US Retail Quick Reference.xlsx"
If (IsWorkbookOpen(path & fileName)) Then
stuff = Workbooks(fileName).Sheets("Quick Reference").Range("A1").Value
Else
' Do Something Else // UNTESTED:
stuff = ExecuteExcel4Macro("'" & path & "[" & fileName & "]" & _
"Quick Reference'!" & Range("A1").Address(True, True, -4150))
' or:
' Dim wb as Workbook
' Set wb = Workbooks.Open(path + fileName)
' stuff = wb.Sheets("Quick Reference").Range("A1").Value
' wb.Close
End If
对于" Something Else",我建议使用ExecuteExcel4Macro
method for obtaining value from a closed workbook。