7.1 设置阶段

代码清单7.1:使用Parent属性获得一个对象的父对象的指针

'使用Parent属性获得一个对象的父对象的指针
Sub MeetMySingleParent()
'Declare a worksheet variable named ws
Dim ws As Worksheet 'set ws to refer to sheet 1
Set ws = ThisWorkbook.Worksheets("Sheet1") 'please meet my parent - Mrs. Workbook
Debug.Print ws.Parent.Name Set ws = Nothing
End Sub

以编程方式区分出代码名称和实际名称

'prints out name & code name
'assumes a worksheet has been named
'in the vbe as: wsMenu Dim wsMenu As Worksheet ' = ThisWorkbook.Worksheets(1)
Sub WhatsMyName()
On Error Resume Next Debug.Print "The name on my worksheet tab is " & wsMenu.Name & ", " & vbCrLf
Debug.Print "But you can call me " & wsMenu.CodeName
End Sub

7.2 在使用工作表之前确认它们

代码清单7.2:确认一个工作表名称在使用其之前已存在

'代码清单7.2:确认一个工作表名称在使用其之前已存在
Function WorksheetExists(wb As Workbook, sName As String) As Boolean
Dim s As String
On Error GoTo bWorksheetExistsErr
s = wb.Worksheets(sName).Name
WorksheetExists = True
Exit Function
bWorksheetExistsErr:
WorksheetExists = False
End Function

代码清单7.3:使用函数检查代码名称的存在性

'determines if a given worksheet name exists in a workbook
'checks by looking for the code name rather than the name
Function WorksheetCodenameExists(wb As Workbook, sCodename As String) As Boolean
Dim s As String
Dim ws As Worksheet WorksheetCodenameExists = False
For Each ws In wb.Worksheets
If StrComp(ws.CodeName, sCodename, vbTextCompare) = Then
WorksheetCodenameExists = True
Exit For
End If
Next
Set ws = Nothing
End Function

7.3 隐藏与取消隐藏

代码清单7.4:隐藏和取消隐藏工作表

'代码清单7.4: 隐藏和取消隐藏工作表
'/Hides the worksheet named sName
Sub HideWorksheet(sName As String, bVeryHidden As Boolean)
If WorksheetExists(ThisWorkbook, sName) Then
If bVeryHidden Then
ThisWorkbook.Worksheets(sName).Visible = xlSheetVeryHidden
Else
ThisWorkbook.Worksheets(sName).Visible = xlSheetHidden
End If
End If
End Sub Sub UnhideWorksheet(sName As String)
If WorksheetExists(ThisWorkbook, sName) Then
ThisWorkbook.Worksheets(sName).Visible = xlSheetVisible
End If
End Sub Sub UsingHideUnhide()
Dim lResponse As Long 'Hide the worksheet
HideWorksheet "Sheet2", True 'Show that it is hidden - ask to unhide
lResponse = MsgBox("the worksheet is very hidden. unhide?", vbYesNo) If lResponse = vbYes Then
UnhideWorksheet "Sheet2"
End If
End Sub

代码清单7.5:取消隐藏工作薄中的每一个工作表

'代码清单7.5: 取消隐藏工作薄中的每一个工作表
'Unhides all worksheets in the workbook, even very hidden worksheets
Sub UnhideAllWorksheets()
Dim ws As Worksheet For Each ws In ThisWorkbook.Worksheets
ws.Visible = xlSheetVisible
Next ws Set ws = Nothing
End Sub

7.4 锁住关键内容

代码清单7.6:利用Protect方法保护工作表

'代码清单7.6: 利用Protect方法保护工作表
Function ProtectWorksheet(ws As Worksheet, sPassword As String) As Boolean
On Error GoTo ErrHandler
If Not ws.ProtectContents Then
ws.Protect sPassword, True, True, True
End If ProtectWorksheet = True
Exit Function
ErrHandler:
ProtectWorksheet = False
End Function

代码清单7.7:利用Unprotect方法解除工作表保护

'代码清单7.7: 利用Unprotect方法解除工作表保护
Function UnprotectWorksheet(ws As Worksheet, sPassword As String) As Boolean
On Error GoTo ErrHandler
If ws.ProtectContents Then
ws.Unprotect sPassword
End If
UnprotectWorksheet = True
Exit Function
ErrHandler:
UnprotectWorksheet = False
End Function Sub TestProtection()
Dim ws As Worksheet
Set ws = ThisWorkbook.Worksheets() 'example of how you might use protectworksheet
If Not ProtectWorksheet(ws, "TestPassword") Then
Debug.Print "the worksheet could not be protected."
Else
Debug.Print "the worksheet has been protected."
End If 'example of how you might use unprotect worksheet
If UnprotectWorksheet(ws, "testpassword") Then
'unprotected - safe to modify the worksheet
'contents pogrammatically now...
Debug.Print "the worksheet has been unprotected."
Else
Debug.Print "the worksheet could not be unprotected."
End If Set ws = Nothing
End Sub

7.5 管理工作薄工作表

7.5.1 增加和删除工作表

增加工作表的语法:

ThisWorkbook.Worksheets.Add [Before|After],[Count],[Type]

VBA调用方法或函数除了按位置设置实参,还可以按名称设置实参,当指定参数名称时,不需要按照顺序放置参数。

'通过名称指定参数
ThisWorkbook.Worksheets.Add Count:=, Before:= ThisWorkbook.Worksheets()
'通过顺序指定参数
ThisWorkbook.Worksheets.Add ThisWorkbook.Worksheets(), ,

删除工作表的实例:

Sub TestDelete()
'删除工作薄的第一个工作表
ThisWorkbook.Worksheets().Delete
End Sub

上面代码执行,可能会弹出删除工作表的确认对话框。可以通过Application对象的DisplayAlerts属性关闭这个功能。

代码清单7.8:使用DeleteSheet函数安全删除工作表

'Deletes the worksheet given in the ws parameter
'if bQuiet then do not display Excel alerts
Function DeleteSheet(ws As Worksheet, bQuiet As Boolean) As Boolean
Dim bDeleted As Boolean On Error GoTo ErrHandler bDeleted = False If CountVisibleSheets(ws.Parent) > Then
'ok to delete - display alerts?
If bQuiet Then Application.DisplayAlerts = False 'finally! delete the darn thing
bDeleted = ws.Parent.Worksheets(ws.Name).Delete
Else
'forget it -
'need at least one visible sheet in a workbook,
'bDeleted is already false
End If ExitPoint:
'make sure display alerts is always on
Application.DisplayAlerts = True
DeleteSheet = bDeleted
Exit Function ErrHandler:
bDeleted = False
Resume ExitPoint
End Function 'returns a count of all of the visible sheets in the workbook wb
Function CountVisibleSheets(wb As Workbook) As Integer
Dim nSheetIndex As Integer
Dim nCount As Integer
nCount =
For nSheetIndex = To wb.Sheets.Count
If wb.Sheets(nSheetIndex).Visible = xlSheetVisible Then
nCount = nCount +
End If
Next
CountVisibleSheets = nCount
End Function

7.5.2 移动和复制工作表

移动和复制工作表的语法:

worksheet.Move [Before|After]

worksheet.Copy [Before|After]

Before|After是Worksheet对象,如果没有指定,则worksheet被放置到一个新建的工作薄中。

Sub SimpleWorksheetMovement()
'复制第3个工作表到新建的工作薄
ThisWorkbook.Worksheets().Copy
'复制第3个工作表到第2个工作表之前
ThisWorkbook.Worksheets().Copy ThisWorkbook.Worksheets()
'移动第2个工作表到工作薄的末尾
ThisWorkbook.Worksheets().Move _
After := ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)
End Sub

代码清单7.9:在工作薄中按字母顺序排序工作表

'代码清单7.9: 在工作薄中按字母顺序排序工作表
'performs a simple bubble sort to
'sort the worksheets in the workbook
Sub AlphabetizeWorksheets(wb As Workbook)
Dim bSorted As Boolean
Dim nSheetsSorted As Integer
Dim nSheets As Integer
Dim n As Integer nSheets = wb.Worksheets.Count
nSheetsSorted = Do While (nSheetsSorted < nSheets) And Not bSorted
bSorted = True
nSheetsSorted = nSheetsSorted +
For n = To nSheets - nSheetsSorted
If StrComp(wb.Worksheets(n).Name, wb.Worksheets(n + ).Name, vbTextCompare) > Then
'out of order - swap the sheets
wb.Worksheets(n + ).Move beforfore:=wb.Worksheets(n)
bSorted = False
End If
Next
Loop
End Sub

7.6 说明工作表事件

在选择响应的事件之前,确认在工程浏览器中选择了适当的工作表

代码清单7.10:使用Change事件响应工作表改变

Private Sub Worksheet_Change(ByVal Target As Range)
Select Case Target.Address
Case "$B$1"
ChangeColumnWidth Target.Value
Case "$B$2"
ChangeRowHeight Target.Value
End Select
End Sub Sub ChangeColumnWidth(Width As Variant)
If IsNumeric(Width) Then
If < Width And Width < Then
Me.Columns.ColumnWidth = Width
ElseIf Width = Then
Me.Columns.ColumnWidth = Me.StandardWidth
End If
End If
End Sub Sub ChangeRowHeight(Height As Variant)
If IsNumeric(Height) Then
If < Height And Height < Then
Me.Rows.RowHeight = Height
ElseIf Height = Then
Me.Rows.RowHeight = Me.StandardHeight
End If
End If
End Sub

注意,清单中的Me代表Worksheet。

7 Worksheet 对象的更多相关文章

  1. 【VBA编程】15.WorkSheet对象常用属性

    [Cells属性] Cells属性用于返回一个Range对象,表示工作表中所有的单元格,包括已经使用的单元格和未使用的单元格. [代码区域] Sub 使用Cells属性() '声明变量 Dim wk ...

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

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

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

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

  4. Excel VBA入门(五)Excel对象操作

    本章是本系列教程的重点.但我觉得应该不是难点.从第零章开始到学完本章,应该可以把VBA用于实战中了. Excel对象主要有4个: 工作薄 Workbook 工作表 Worksheet 单元格区域 Ra ...

  5. Excel Application对象应用

    Application对象是Excel对象模型中最高层级的对象,代表Excel应用程序自身,也包含组成工作簿的许多部分,包括工作簿.工作表.单元格集合以及它们包含的数据. Application对象包 ...

  6. Excel开发学习笔记:查找与创建worksheet

    开发环境基于VSTO,具体配置:visual studio 2010,VB .Net,excel 2007,文档级别的定制程序. 如题,我在ThisWorkbook.vb中添加了一个public函数来 ...

  7. 8 Range 对象

    8.1 引用Range 引用Range的主要方法: Application.ActiveCell Application.Range Application.Selection Worksheet.C ...

  8. Python 操作 MS Excel 文件

    利用 Python 对 Excel 文件进行操作需要使用第三方库: openpyxl,可执行 pip install openpyxl 进行安装 1. 导入 openpyxl 模块 导入 openpy ...

  9. VBA常用代码解析

    031 删除工作表中的空行 如果需要删除工作表中所有的空行,可以使用下面的代码. Sub DelBlankRow() DimrRow As Long DimLRow As Long Dimi As L ...

随机推荐

  1. [转]Delphi调用cmd并取得输出文本

    //转自http://www.oschina.net/code/snippet_136241_3980 1 procedure CheckResult(b: Boolean); begin if no ...

  2. 升级openssh踩得坑

    升级背景: 项目中使用的系统为CentOS6.8,经过漏洞扫描后发现openssh高危漏洞,具体描述如下:OpenSSH 7.2p2之前版本, sshd/ session.c/ do_setup_en ...

  3. MySQL-----增

    增 **创建用户** create user 'alex'@'192.168.1.1' identified by '123123'; create user 'alex'@'192.168.1.%' ...

  4. axios增加的自定义header,后端request取不到

    1.拦截器配置 <!--拦截器--> <mvc:interceptors> <!-- web端增加头部接口 --> <mvc:interceptor> ...

  5. 姓名与ID(codevs 1027 未结题)

    题目描述 Description 有N个人,各自有一个姓名和ID(别名).每个人的姓名和ID都没有重复.这些人依次进入一间房间,然后可能会离开.过程中可以得到一些信息,告知在房间里的某个人的ID.你的 ...

  6. [USACO5.3]巨大的牛棚Big Barn

    题目背景 (USACO 5.3.4) 题目描述 农夫约翰想要在他的正方形农场上建造一座正方形大牛棚.他讨厌在他的农场中砍树,想找一个能够让他在空旷无树的地方修建牛棚的地方.我们假定,他的农场划分成 N ...

  7. 自定义View实现跟随手指的小球

    package com.pingyijinren.test; import android.content.Context; import android.graphics.Canvas; impor ...

  8. TensorFlow-GPU环境配置之二——CUDA环境配置

    1.安装最新显卡驱动 到系统设置->软件和更新->附加驱动中选中最新的显卡驱动,并应用 2.下载CUDA8.0 https://developer.nvidia.com/cuda-down ...

  9. C# 图片识别(支持21种语言)转

    来自:http://www.cnblogs.com/stone_w/archive/2011/10/08/2202397.html 图片识别的技术到几天已经很成熟了,只是相关的资料很少,为了方便在此汇 ...

  10. ArcEngine 打开AutoCAD文件的几种方法

    方法一. IWorkspaceFactory pWorkspaceFactory; IFeatureWorkspace pFeatureWorkspace; IFeatureLayer pFeatur ...