6.1 在奔跑之前先学会走路:打开和关闭工作薄

代码清单6.1:一个完整的工作薄批处理框架

  1. '代码清单6.1:一个完整的工作薄批处理框架
  2. Sub ProcessFileBatch()
  3. Dim nIndex As Integer
  4. Dim vFiles As Variant
  5. Dim wb As Workbook
  6. Dim bAlreadyOpen As Boolean
  7.  
  8. On Error GoTo ErrHandler
  9.  
  10. 'Get a batch of Excel files
  11. vFiles = GetExcelFiles("Select Workbooks for Processing" )
  12.  
  13. 'Make sure the dialog wasn't cancelled - in which case
  14. 'vFiles would equal False and therefore wouldn't be an array.
  15. If Not IsArray(vFiles) Then
  16. Debug.Print "No files Selected."
  17. Exit Sub
  18. End If
  19.  
  20. Application.ScreenUpdating = False
  21.  
  22. 'OK - loop through the filenames
  23. For nIndex = To UBound (vFiles)
  24.  
  25. If isWorkbookOpen(CStr(vFiles(nIndex))) Then
  26. Set wb = Workbooks(GetShortName(CStr (vFiles(nIndex))))
  27. Debug.Print "workbook already open: " & wb.Name
  28. bAlreadyOpen = True
  29.  
  30. Else
  31. Set wb = Workbooks.Open(CStr(vFiles(nIndex)), False )
  32. Debug.Print "Opened workbook: " & wb.Name
  33. bAlreadyOpen = False
  34.  
  35. End If
  36.  
  37. Application.StatusBar = "processing workbook: " & wb.Name
  38.  
  39. 'code to process the file goes here
  40. Debug.Print "if we wanted to do something to the workbook, we would do it here"
  41.  
  42. 'close workbook unless it was already open
  43. If Not bAlreadyOpen Then
  44. Debug.Print "closing workbook: " & wb.Name
  45. wb.Close True
  46. End If
  47. Next nIndex
  48.  
  49. Set wb = Nothing
  50. ErrHandler:
  51. Application.StatusBar = False
  52. Application.ScreenUpdating = True
  53.  
  54. End Sub

6.2 工作薄打开了吗

代码清单6.2:查看一个工作薄是否是打开的

  1. '代码清单6.2: 查看一个工作薄是否是打开的
  2. ' This function checks to see if a given workbook
  3. ' is open or not. this function can be used
  4. ' using a short name such as MyWorkbook.xls
  5. ' or a full name such as C: \Testing\MyWorkbook.xls
  6. Function isWorkbookOpen(sWorkbook As String) As Boolean
  7. Dim sName As String
  8. Dim sPath As String
  9. Dim sFullName As String
  10.  
  11. On Error Resume Next
  12. isWorkbookOpen = True
  13.  
  14. 'see if we were given a short name or a long name
  15. If InStr(, sWorkbook, "\", vbTextCompare) > Then
  16. 'we have a long name need to break it down
  17. sFullName = sWorkbook
  18.  
  19. 'BreakdownName参见代码清单5.8
  20. BreakdownName sFullName, sName, sPath
  21. If StrComp(Workbooks(sName).FullName, sWorkbook, vbTextCompare) <> Then
  22. isWorkbookOpen = False
  23. End If
  24. Else
  25. 'we have a short name
  26. If StrComp(Workbooks(sWorkbook).Name, sWorkbook, vbTextCompare) <> Then
  27. isWorkbookOpen = False
  28. End If
  29. End If
  30.  
  31. End Function

另一个IsWorkbookOpen:

  1. Function IsWorkbookOpen(sWorkbookName AsString) As Boolean
  2. Dim wb As Workbook
  3.  
  4. IsWorkbookOpen = False
  5. For Each wb In Workbooks
  6. If StrComp(sWorkbookName, wb.Name, vbTextCompare) = Then
  7. IsWorkbookOpen = True
  8. Exit Function
  9. End If
  10. Next
  11. Set wb =Nothing
  12. End Function

三个VBA字符串函数:

InStr([start, ]string1, string2[, compare]): 指出string2在string1中第一次出现的位置。

InStrRev(string1, string2[, compare]): 指出string2在string1中最后一次出现的位置。

StrComp(string1, string2[, compare]): 比较两个字符串,返回-1、0、1中的值。

说明:

VBA中,字符串的索引是基于0的。

compare可以取值vbTextCompare或者vbBinaryCompare,前者表示不区分大小写,后者表示区分大小写。compare的默认值为vbUseCompareOption,就是取模块选项的设置。

6.2.1 指定特定的集合对象

下面的例子示范了可以指向集合中的一个项目的4种方法。这个例子使用Worksheets集合对象。

  1. Sub ReferringToItems()
  2. 'refer to a worksheet by index number
  3. Debug.Print ThisWorkbook.Worksheets( ).Name
  4. 'once again, but with feeling
  5. Debug.Print ThisWorkbook.Worksheets.Item( ).Name
  6.  
  7. 'refer to a worksheet by name
  8. Debug.Print ThisWorkbook.Worksheets("Sheet1" ).Name
  9. 'and gain using item ...
  10. Debug.Print ThisWorkbook.Worksheets.Item("Sheet1" ).Name
  11.  
  12. End Sub

6.3以编程方式解开链接(第1部分)

代码清单6.3:以程序设计方式得到链接资源信息

  1. '代码清单6.3:以程序设计方式得到链接资源信息
  2. Sub PrintSimpleLinkInfo(wb As Workbook)
  3. Dim avLinks As Variant
  4. Dim nIndex As Integer
  5.  
  6. 'get list of excel based link sources
  7. avLinks = wb.LinkSources(xlExcelLinks)
  8. If Not IsEmpty(avLinks) Then
  9. 'loop through every link source
  10. For nIndex = To UBound (avLinks)
  11. Debug.Print "link found to '" & avLinks(nIndex) & "'"
  12. Next nIndex
  13. Else
  14. Debug.Print "the workbook '" & wb.Name & "' don't have any links."
  15. End If
  16.  
  17. End Sub

代码清单6.4:用新的文件位置更新链接

  1. '代码清单6.4: 用新的文件位置更新链接
  2. Sub fixLinks(wb As Workbook, sOldLink As String, sNewLink As String )
  3. On Error Resume Next
  4. wb.ChangeLink sOldLink, sNewLink, xlLinkTypeExcelLinks
  5.  
  6. End Sub

代码清单6.5:用新的文件位置更新链接(一个替代过程)

  1. '代码清单6.5: 用新的文件位置更新链接—一个替代过程
  2. Sub FixLinksII(wb As Workbook, sOldLink As String, sNewLink As String )
  3. Dim avLinks As Variant
  4. Dim nIndex As Integer
  5.  
  6. 'get a list of link sources
  7. avLinks = wb.LinkSources(xlExcelLinks)
  8.  
  9. 'if there are link sources, see if there are any named sOldLink
  10. If Not IsEmpty(avLinks) Then
  11. For nIndex = To UBound (avLinks)
  12. If StrComp(avLinks(nIndex), sOldLink, vbTextCompare) = Then
  13. 'we have a match
  14. wb.ChangeLink sOldLink, sNewLink, xlLinkTypeExcelLinks
  15. 'once we find a match we won't find another, so exit the loop
  16. Exit For
  17. End If
  18. Next
  19. End If
  20.  
  21. End Sub

代码清单6.6:链接状态查看器

  1. '代码清单6.6: 链接状态查看器
  2. Function GetLinkStatus(wb As Workbook, sLink As String) As String
  3. Dim avLinks As Variant
  4. Dim nIndex As Integer
  5. Dim sResult As String
  6. Dim nStatus As Integer
  7.  
  8. 'get a list of link sources
  9. avLinks = wb.LinkSources(xlExcelLinks)
  10.  
  11. 'make sure there are links in the workbook
  12. If IsEmpty(avLinks) Then
  13. GetLinkStatus = "No links in workbook."
  14. Exit Function
  15. End If
  16.  
  17. 'default result in case the links is not found
  18. sResult = "link not found"
  19.  
  20. For nIndex = To UBound (avLinks)
  21. If StrComp(avLinks(nIndex), sLink, vbTextCompare) = Then
  22. nStatus = wb.LinkInfo(sLink, xlLinkInfoStatus)
  23.  
  24. Select Case nStatus
  25. Case xlLinkStatusCopiedValues
  26. sResult = "Copied values"
  27.  
  28. Case xlLinkStatusIndeterminate
  29. sResult = "Indeterminnate"
  30.  
  31. Case xlLinkStatusInvalidName
  32. sResult = "Invalid name"
  33.  
  34. Case xlLinkStatusMissingFile
  35. sResult = "Missing file"
  36.  
  37. Case xlLinkStatusMissingSheet
  38. sResult = "Missing sheet"
  39.  
  40. Case xlLinkStatusNotStarted
  41. sResult = "Not started"
  42.  
  43. Case xlLinkStatusOK
  44. sResult = "OK"
  45.  
  46. Case xlLinkStatusOld
  47. sResult = "Old"
  48.  
  49. Case xlLinkStatusSourceNotCalculated
  50. sResult = "Source Not Calculated"
  51.  
  52. Case xlLinkStatusSourceNotOpen
  53. sResult = "Source Not Open"
  54.  
  55. Case xlLinkStatusSourceOpen
  56. sResult = "Source Open"
  57.  
  58. Case Else
  59. sResult = "Unknown status code"
  60. End Select
  61. End If
  62. Next
  63.  
  64. End Function

代码清单6.7:查看一个工作薄中所有的链接状态

  1. '代码清单6.7: 查看一个工作薄中所有的链接状态
  2. Sub CheckAllLinks(wb As Workbook)
  3. Dim avLinks As Variant
  4. Dim nLinkIndex As Integer
  5. Dim sMsg As String
  6.  
  7. avLinks = wb.LinkSources(xlExcelLinks)
  8.  
  9. If IsEmpty(avLinks) Then
  10. Debug.Print wb.Name & " does not have any links."
  11. Else
  12. For nLinkIndex = To UBound (avLinks)
  13. Debug.Print "workbook: " & wb.Name
  14. Debug.Print "link source: " & avLinks(nLinkIndex)
  15. Debug.Print "status: " & GetLinkStatus(wb, CStr (avLinks(nLinkIndex)))
  16. Next
  17. End If
  18.  
  19. End Sub

6.4 简单普通的工作薄属性

代码清单6.8:一个标准工作薄属性的简单例子

  1. '代码清单6.8: 一个标准工作薄属性的简单例子
  2. Sub TestPrintGeneralWBInfo()
  3. PrintGeneralWorkbookInfo ThisWorkbook
  4. End Sub
  5.  
  6. Sub PrintGeneralWorkbookInfo(wb As Workbook)
  7. Debug.Print "Name: " & wb.Name
  8. Debug.Print "Full Name: " & wb.FullName
  9. Debug.Print "Code Name: " & wb.CodeName
  10. Debug.Print "File Format: " & GetFileFormat(wb)
  11. Debug.Print "path: " & wb.Path
  12.  
  13. If wb.ReadOnly Then
  14. Debug.Print " the workbook has been opened as read-only."
  15. Else
  16. Debug.Print " the workbook is read-write."
  17. End If
  18.  
  19. If wb.Saved Then
  20. Debug.Print "the workbook does not need to be saved."
  21. Else
  22. Debug.Print " the workbook should be saved."
  23. End If
  24. End Sub
  25.  
  26. Function GetFileFormat(wb As Workbook) As String
  27. Dim lFormat As Long
  28. Dim sFormat As String
  29. lFormat = wb.FileFormat
  30. Select Case lFormat
  31. Case xlAddIn: sFormat = "Add-In"
  32.  
  33. Case xlCSV: sFormat = "CSV"
  34. Case xlCSVMac: sFormat = "CSV Mac"
  35. Case xlCSVMSDOS: sFormat = "CSV MSDOS"
  36. Case xlCSVWindows: sFormat = "CSV Windows"
  37.  
  38. Case xlCurrentPlatformText: sFormat = "Current Platform Text"
  39.  
  40. Case xlDBF2: sFormat = "DBF 2"
  41. Case xlDBF3: sFormat = "DBF 3"
  42. Case xlDBF4: sFormat = "DBF 4"
  43.  
  44. Case xlDIF: sFormat = "xlDIF"
  45. Case xlExcel2: sFormat = "xlExcel2"
  46. Case xlExcel2FarEast: sFormat = "xlExcel2FarEast"
  47. Case xlExcel3: sFormat = "xlExcel3"
  48. Case xlExcel4: sFormat = "xlExcel4"
  49. Case xlExcel4Workbook: sFormat = "xlExcel4Workbook"
  50. Case xlExcel5: sFormat = "xlExcel5"
  51. Case xlExcel7: sFormat = "xlExcel7"
  52. Case xlExcel9795: sFormat = "xlExcel9795"
  53.  
  54. Case xlHtml: sFormat = "xlHtml"
  55. Case xlIntlAddIn: sFormat = "xlIntlAddIn"
  56. Case xlSYLK: sFormat = "xlSYLK"
  57. Case xlTemplate: sFormat = "xlTemplate"
  58. Case xlTextMac: sFormat = "xlTextMac"
  59. Case xlTextMSDOS: sFormat = "xlTextMSDOS"
  60. Case xlTextPrinter: sFormat = "xlTextPrinter"
  61. Case xlTextWindows: sFormat = "xlTextWindows"
  62. Case xlUnicodeText: sFormat = "xlUnicodeText"
  63. Case xlWebArchive: sFormat = "xlWebArchive"
  64. Case xlWJ2WD1: sFormat = "xlWJ2WD1"
  65. Case xlWJ3: sFormat = "xlWJ3"
  66. Case xlWJ3FJ3: sFormat = "xlWJ3FJ3"
  67.  
  68. Case xlWK1: sFormat = "xlWK1"
  69. Case xlWK1ALL: sFormat = "xlWK1ALL"
  70. Case xlWK1FMT: sFormat = "xlWK1FMT"
  71. Case xlWK3: sFormat = "xlWK3"
  72. Case xlWK3FM3: sFormat = "xlWK3FM3"
  73. Case xlWK4: sFormat = "xlWK4"
  74. Case xlWKS: sFormat = "xlWKS"
  75. Case xlWorkbookNormal: sFormat = "xlWorkbookNormal"
  76. Case xlWorks2FarEast: sFormat = "xlWorks2FarEast"
  77. Case xlWQ1: sFormat = "xlWQ1"
  78. Case xlXMLSpreadsheet: sFormat = "xlXMLSpreadsheet"
  79.  
  80. Case Else
  81. sFormat = "Unknown format code"
  82. End Select
  83. GetFileFormat = sFormat
  84. End Function

6.5 响应用户动作事件

代码清单6.9:测试Workbook对象事件

  1. Private Sub Workbook_Activate()
  2. If UseEvents Then
  3. MsgBox "Welcome back! ", vbOKOnly, "Activate Event"
  4. End If
  5. End Sub
  6.  
  7. Private Sub Workbook_BeforeClose(Cancel As Boolean )
  8. Dim lResponse As Long
  9.  
  10. If UseEvents Then
  11. lResponse = MsgBox("Thanks for visiting!" & "Are you sure you don't want to stick around?", vbYesNo, "see ya.." )
  12. End If
  13. End Sub
  14.  
  15. Private Sub Workbook_Deactivate()
  16. If UseEvents Then
  17. MsgBox "see you soon...", vbOKOnly, "Deactivate Event"
  18. End If
  19. End Sub
  20.  
  21. Private Sub Workbook_Open()
  22. Dim lResponse As Long
  23. lResponse = MsgBox("Welcome to the Chapter Six Example Workbook! Would you like to use events?", vbYesNo, "Welcome" )
  24.  
  25. If lResponse = vbYes Then
  26. TurnOnEvents True
  27. ElseIf lResponse = vbNo Then
  28. TurnOnEvents False
  29. End If
  30. End Sub
  31.  
  32. Private Sub TurnOnEvents(bUseEvents As Boolean)
  33. On Error Resume Next
  34. If bUseEvents Then
  35. ThisWorkbook.Worksheets().Range("TestEvents").Value = "Yes"
  36. Else
  37. ThisWorkbook.Worksheets().Range("TestEvents").Value = "No"
  38. End If
  39. End Sub
  40.  
  41. Private Function UseEvents() As Boolean
  42. On Error Resume Next
  43.  
  44. UseEvents = False
  45. If UCase(ThisWorkbook.Worksheets().Range("TestEvents").Value) = "YES" Then
  46. UseEvents = True
  47. End If
  48. End Function
  49.  
  50. Private Sub Workbook_SheetActivate(ByVal Sh As Object)
  51. If UseEvents Then
  52. MsgBox "Activated " & Sh.Name, vbOKOnly, "SheetActivate Event"
  53. End If
  54. End Sub
  55.  
  56. Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean )
  57. If UseEvents Then
  58. MsgBox "Ouch! Stop that.", vbOKOnly, "SheetBeforeDoubleClick Event"
  59. End If
  60. End Sub
  61.  
  62. Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean )
  63. If UseEvents Then
  64. MsgBox "Right click " & Sh.Name & "; Target " & Target.Address & "; Cancel " & Cancel, vbOKOnly, "RightClick Event"
  65. End If
  66. End Sub
  67.  
  68. Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
  69. If UseEvents Then
  70. MsgBox "You change the range" & Target.Address & " on " & Sh.Name, vbOKOnly, "Workbook_SheetChange Event"
  71. End If
  72. End Sub
  73.  
  74. Private Sub Workbook_SheetDeactivate(ByVal Sh As Object )
  75. If UseEvents Then
  76. MsgBox "Leaving " & Sh.Name, vbOKOnly, "Workbook_SheetDeactivate Event"
  77. End If
  78. End Sub
  79.  
  80. Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
  81. If UseEvents Then
  82. If Target.Row Mod = Then
  83. MsgBox "I'm keeping my eyes on you! you selected the range " & Target.Address & " on " & Sh.Name, _
  84. vbOKOnly, "Workbook_SheetSelectionChange Event"
  85. Else
  86. MsgBox "you selected the range " & Target.Address & " on " & Sh.Name, _
  87. vbOKOnly, "Workbook_SheetSelectionChange Event"
  88. End If
  89. End If
  90. End Sub

6 Workbook 对象的更多相关文章

  1. Workbook对象的方法总结(一)

    import openpyxlwb=openpyxl.Workbook()print('1.添加前所有工作簿的名称是:',wb.get_sheet_names())wb.create_sheet('F ...

  2. 【VBA编程】13.Workbook对象的事件

    Workbook事件用于响应对Workbook对象所进行的操作. [BeforeClose事件] BforeClose事件用于响应窗口关闭的操作 在工程资源器中,双击“ThisWorkbook”对象, ...

  3. Workbook对象的方法总结(二)

    (1).Worksheet 对象有 row_dimensions 和 column_dimensions 属性,控制行高和列宽. 例如: >>> sheet.row_dimensio ...

  4. 【VBA编程】12.Workbook对象常用属性

    [ActiveSheet属性] ActiveSheet属性用于返回一个对象,表示活动工作簿中或指定的窗口或工作簿中的活动工作表 [Colors] Colors属性是一个Variant类型的可读写属性, ...

  5. POI完美解析Excel数据到对象集合中(可用于将EXCEL数据导入到数据库)

    实现思路: 1.获取WorkBook对象,在这里使用WorkbookFactory.create(is); // 这种方式解析Excel.2003/2007/2010都没问题: 2.对行数据进行解析 ...

  6. 电子表格控件Spreadsheet 对象方法事件详细介绍

    1.ActiveCell:返回代表活动单元格的Range只读对象.2.ActiveSheet:返回代表活动工作表的WorkSheet只读对象.3.ActiveWindow:返回表示当前窗口的Windo ...

  7. Excel 文件转 JSON格式对象

    将导入的如图所示格式的城乡区划代码的excel文件整理成json格式的对象储存在js文件中: var PROJECTDISTRICTDATA=[    {        "name" ...

  8. NPOI:创建Workbook和Sheet

    NPOI官方网站:http://npoi.codeplex.com/ 创建Workbook说白了就是创建一个Excel文件,当然在NPOI中更准确的表示是在内存中创建一个Workbook对象流.在看了 ...

  9. java excel Workbook API

    此文摘自:http://blog.sina.com.cn/zenyunhai 1. int getNumberOfSheets() 获得工作薄(Workbook)中工作表(Sheet)的个数,示例: ...

随机推荐

  1. mysql查询排名

    student_work表 student_info表 sql语句:按grade从高到低排名 结果:

  2. Django的admin源码浅析和模仿

    admin模块: admin提供了5种接口 list_display, 指定数据展示字段,不能放多对多字段

  3. 语法,if,while循环,for循环

    目录 一.语法 二.while循环 三.for循环 一.语法 if: if判断其实是在模拟人做判断.就是说如果这样干什么,如果那样干什么.对于ATM系统而言,则需要判断你的账号密码的正确性. if 条 ...

  4. <struct、union、enum>差异

    关于C++和C的区别 区别最大的是struct,C++中的struct几乎和class一样了,可以有成员函数,而C中的struct只能包含成员变量. enum,union没区别. struct的定义 ...

  5. CodeForcesGym 100512D Dynamic LCA

    Dynamic LCA Time Limit: 2000ms Memory Limit: 262144KB This problem will be judged on CodeForcesGym. ...

  6. [luoguP1086] 花生采摘(模拟)

    传送门 模拟... 代码 #include <cstdio> #include <iostream> #include <algorithm> #define ab ...

  7. HTML5学习之语义化标签

    一.为什么HTML5要引入新语义标签 在HTML5出现之前,我们一般采用DIV+CSS布局我们的页面.但是这样的布局方式不仅使我们的文档结构不够清晰,而且不利于搜索引擎爬虫对我们页面的爬取.为了解决上 ...

  8. Delphi:Indy9的IdFTP完全使用

    Delphi 7自带的INDY控件,其中包含了IdFTP,可以方便的实现FTP客户端程序,参考自带的例子,其中有上传.下载.删除文件,但是不包含对文件夹的操作,得自己实现上传.下载.删除整个文件夹(带 ...

  9. 洛谷——P1062 数列

    洛谷——P1062 数列 题目描述 给定一个正整数k(3≤k≤15),把所有k的方幂及所有有限个互不相等的k的方幂之和构成一个递增的序列,例如,当k=3时,这个序列是: 1,3,4,9,10,12,1 ...

  10. Remove Duplicates from Sorted Array(参考)

    Given a sorted array, remove the duplicates in place such that each element appear only once and ret ...