Excel開發學習筆記:查找與建立worksheet

開發環境基於VSTO,具體配置:visual studio 2010,VB .Net,excel 2007,文檔級別的定製程序。

如題,我在ThisWorkbook.vb中添加了一個public函數來完成查找功能。
函數

入參:待查找的sheet名稱spa

返回:若是存在則返回worksheet對象,若是不存在則返回nothing
     Public  Function WorksheetExist(name  As  StringAs Excel.Worksheet  
         Try  
             Dim existSheet  As Excel.Worksheet = Globals.ThisWorkbook.Sheets(name)  
             Return existSheet  
         Catch ex  As Exception  
             Return  Nothing  
         End  Try  
      
     End Function 

 

 

建立worksheet函數,要求在現有sheet的尾部添加新的sheet。

入參:Workbook,新sheet名excel

返回:成功則返回新的sheet對象,失敗返回nothingcode

     Private  Function CreatWorksheet( ByRef book  As Excel.Workbook,  ByRef name  As  StringAs Excel.Worksheet  
         Dim newSheet  As Excel.Worksheet = book.Sheets.Add(After:=book.Worksheets(book.Sheets.Count))  
         Try  
      
            newSheet.Name = name  
             Return newSheet  
         Catch ex  As Exception  
             MsgBox( " "" " + name +  " "" " +  " 不能被用做excel工做表(sheet)名稱 ")  
            newSheet.Delete()  
             Return  Nothing  
         End  Try  
      
     End Function 

 

 查詢與建立連起來使用,未查找到則建立的代碼片斷:對象

     Dim algoSheet  As Excel.Worksheet = Globals.ThisWorkbook.WorksheetExist(name)  
     If algoSheet  Is  Nothing  Then  
        algoSheet = CreatWorksheet(Globals.ThisWorkbook.Application.Workbooks(Globals.ThisWorkbook.Name), name)  
         If (algoSheet  Is  NothingThen  
             Continue  For  
         End  If  
     End  If 
相關文章
相關標籤/搜索