代码1 - 新建、保存工作簿
cpp
Sub WorkbooksTest()
' 创建工作簿
'Workbooks.Add
' 创建工作簿并保存至本地
Workbooks.Add.SaveAs Filename:="C:\Users\jxd\Desktop\workbook.xlsx"
End Sub
代码2 - 打开、保存、关闭工作簿
cpp
Sub WorkbooksTest()
' 打开工作簿
'Workbooks.Open Filename:="xxx/Test.xlsx"
' 保存刚打开后且已修改的工作簿
Workbooks("xxx/Test.xlsx").Save
' 关闭工作簿
Workbooks.Close
End Sub
代码3 - 删除工作簿
cpp
Sub WorkbooksTest()
' 创建工作簿并保存至本地
Workbooks.Add.SaveAs Filename:="C:\Users\jxd\Desktop\workbook.xlsx"
' 关闭当前活动的工作簿
ActiveWorkbook.Close
' 删除工作簿
Kill PathName:="C:\Users\jxd\Desktop\workbook.xlsx"
End Sub
代码4 - 工作簿名称、路径信息
cpp
Option Explicit
Sub WorkbooksTest()
' ThisWorkbook.Path:默认工作簿路径(路径不包含文件名)
Range("D2").Value = ThisWorkbook.Path
' ActiveWorkbook.Path:当前活动的工作簿路径(路径不包含文件名)
Range("B2").Value = ActiveWorkbook.Path
' ActiveWorkbook.Name:当前活动的工作簿路径(不包含路径)
MsgBox ThisWorkbook.NameMsgBox = ActiveWorkbook.Name
' ActiveWorkbook.FulIName:当前活动的工作簿路径(路径+文件名)
MsgBox ThisWorkbook.FullNameMsgBox = ActiveWorkbook.FulIName
' 打开路径组合的工作簿
Workbooks.Open Filename:=ThisWorkbook.Path & "\" & "案例.xls"
End Sub
代码5 - 使用ForEach遍历工作簿
cpp
Sub WorkbooksTest()
Dim book As Workbook
For Each book In Workbooks
MsgBox book.Name
Next book
End Sub
关注
笔者 - jxd