我有一个字符串" sFile"用扩展名存储工作簿的名称。
我想激活此工作簿,存储在字符串中。
然后关闭它。
使用的代码是:
Dim wbk as workbook
Set wbk = Workbooks(sFile)
wbk.Activate
wbk.close
但这不起作用。请帮助。
答案 0 :(得分:1)
正如评论中所提到的,它只需要名称(不是路径) - 这应该为你做:
Dim wbk as workbook
Set wbk = Workbooks(right(sFile,Instrrev(sFile,"\")+1))
wbk.Activate
wbk.close
答案 1 :(得分:0)
你需要看看你是否成功Set wbk = Workbooks(sFile)
,它只有在工作簿开放时才会起作用。
如果它没有成功(wbk Is Nothing
),那么您需要打开工作簿。
<强>代码强>
Option Explicit
Sub SetWB_toOpenWorkbook()
Dim wbk As Workbook
Dim sFile As String
Dim FilePath As String
' just an example of my file name (clean with extension)
sFile = "SO_1.xlsm"
' set the Dektop path
FilePath = "C:\Users\" & Environ("USERNAME") & "\Desktop\"
On Error Resume Next
Set wbk = Workbooks(sFile)
On Error GoTo 0
If wbk Is Nothing Then ' if not open, then open the workbook
Set wbk = Workbooks.Open(FilePath & sFile)
End If
' just for my tests, put the workbook name in "A1" in "Sheet1"
wbk.Worksheets("Sheet1").Range("A1").Value = wbk.Name
wbk.Activate
wbk.Close True
End Sub