如果要访问已经打开的工作簿,则从Workbooks集合中获取任务很简单:
dim myWB as Workbook Set myWB = Workbooks("UsuallyFullPathnameOfWorkbook.xlsx")
如果要创建新的工作簿,请使用Workbooks集合对象Add创建新的条目。
Dim myNewWB as Workbook Set myNewWB = Workbooks.Add
有时您可能不会或(或不在乎)您所需的工作簿是否已打开,或者可能不存在。示例函数展示了如何始终返回有效的工作簿对象。
Option Explicit Function GetWorkbook(ByVal wbFilename As String) As Workbook '--- returns a workbook object for the given filename, including checks ' for when the workbook is already open, exists but not open, or ' does not yet exist (and must be created) ' *** wbFilename must be a fully specified pathname Dim folderFile As String Dim returnedWB As Workbook '--- check if the file exists in the directory location folderFile = File(wbFilename) If folderFile = "" Then '--- the workbook doesn't exist, so create it Dim pos1 As Integer Dim fileExt As String Dim fileFormatNum As Long '--- in order to save the workbook correctly, we need to infer which workbook ' type the user intended from the file extension pos1 = InStrRev(sFullName, ".", , vbTextCompare) fileExt = Right(sFullName, Len(sFullName) - pos1) Select Case fileExt Case "xlsx" fileFormatNum = 51 Case "xlsm" fileFormatNum = 52 Case "xls" fileFormatNum = 56 Case "xlsb" fileFormatNum = 50 Case Else Err.RaisevbObjectError + 1000, "GetWorkbook function", _ "The file type you've requested (file extension) is not recognized. " & _ "Please use a known extension: xlsx, xlsm, xls, or xlsb." End Select Set returnedWB = Workbooks.Add Application.DisplayAlerts= False returnedWB.SaveAsfilename:=wbFilename, FileFormat:=fileFormatNum Application.DisplayAlerts= True Set GetWorkbook = returnedWB Else '--- the workbook exists in the directory, so check to see if ' it's already open or not On Error Resume Next Set returnedWB = Workbooks(sFile) If returnedWB Is Nothing Then Set returnedWB = Workbooks.Open(sFullName) End If End If End Function