10 探索其他Excel对象
10.1 产生一个好的第一印象
10.1.1 为我们的世界着色
rgb(red:=[0,225],green:=[0,225],blue:=[0,225])
此函数生成一个表示颜色的整数。VBA预定义了一些少量的颜色值,如vbBlack, vbRed等。
代码清单10.1:颜色的乐趣
Sub ColorWorksheet()
Dim ws As Worksheet
Dim lRow As Long
Dim lColumn As Long
Dim lColor As Long Set ws = ThisWorkbook.Worksheets()
lRow =
lColumn = Application.ScreenUpdating = False
Application.StatusBar = "On column " & lColumn '256 * 256 * 256 - 1
For lColor = To * * -
'record color
ws.Cells(lRow, lColumn).Interior.Color = lColor 'move to next cell
lRow = lRow + 'worksheet has 65,536 rows
If lRow = Then
lRow =
lColumn = lColumn +
Application.StatusBar = "On column " & lColumn
End If
Next Set ws = Nothing
Application.ScreenUpdating = True
Application.StatusBar = False
End Sub
能够显示一个颜色的对象都有一个ColorIndex属性。属性ColorIndex的值相当于颜色面板的一个索引。颜色面板是每个工作薄专有的。
10.1.2 字体的细微之处
Font对象表示字体。常用属性有Bold, Color, Italic, Name, Size, Underline等。关于Font对象的详细信息,参见:http://msdn.microsoft.com/en-us/library/ff840959(v=office.15).aspx
代码清单10.2:Font对象—一个简单、直观的对象
Sub DemonstrateFontObject()
Dim nColumn As Long
Dim nRow As Long
Dim avFonts As Variant Dim avColors As Variant For nColumn = To
With ThisWorkbook.Worksheets().Columns(nColumn).Font
.Size = nColumn +
If nColumn Mod = Then
.Bold = True
.Italic = False
Else
.Bold = False
.Italic = True
End If
End With
Next avFonts = Array("Tahoma", "Arial", "MS Sans Serif", "Verdana", "Georgia")
avColors = Array(vbRed, vbBlue, vbBlack, vbGreen, vbYellow)
For nRow = To
With ThisWorkbook.Worksheets().Rows(nRow).Font
.Color = avColors(nRow - )
.Name = avFonts(nRow - ) If nRow Mod = Then
.Underline = True
Else
.Underline = False
End If
End With
Next
End Sub
10.1.3 内部布置
Interior对象代表一个范围或者其他对象的背景。参见:http://msdn.microsoft.com/en-us/library/ff196598(v=office.15).aspx
代码清单10.3:使用Interior对象改变一个范围的背景
Sub InteriorExample()
Dim rg As Range 'create examples of each pattern
Set rg = ThisWorkbook.Worksheets("Interior").Range("ListStart").Offset(, ) Do Until IsEmpty(rg)
rg.Offset(, ).Interior.Pattern = rg.Offset(, ).Value
rg.Offset(, ).Interior.Pattern = rg.Offset(, ).Value
rg.Offset(, ).Interior.PatternColor = vbRed
Set rg = rg.Offset(, )
Loop 'create example of each vb defined color constant
Set rg = ThisWorkbook.Worksheets("Interior").Range("ColorListStart").Offset(, )
Do Until IsEmpty(rg)
rg.Offset(, ).Interior.Color = rg.Offset(, ).Value
Set rg = rg.Offset(, )
Loop
Set rg = Nothing End Sub
以上例子应该从帮助文件中复制常数名称和对应值粘贴到名称(第一列)与值(第二列)列。
代码清单10.4:漫步通过颜色面板
Sub ViewWorkbookColors()
Dim rg As Range
Dim nIndex As Long Set rg = ThisWorkbook.Worksheets("Interior").Range("ColorIndexListStart").Offset(, ) For nIndex = To
rg.Value = nIndex
rg.Offset(, ).Interior.ColorIndex = nIndex
rg.Offset(, ).Value = rg.Offset(, ).Interior.Color Set rg = rg.Offset(, )
Next
Set rg = Nothing
End Sub
工作薄的颜色面板保存了56个颜色,颜色索引的范围是1到56。
10.1.4 这些边界不需要签证
Range对象有一个Borders属性和BordersAround方法。它们被用来操作Range的边框。Borders属性返回Border对象的集合。
Range.Borders属性,参见:http://msdn.microsoft.com/en-us/library/ff822605(v=office.15).aspx
Borders对象,参见:http://msdn.microsoft.com/en-us/library/ff837809(v=office.15).aspx
Border对象,参见:http://msdn.microsoft.com/en-us/library/ff838428(v=office.15).aspx
代码清单10.5:与Border对象相关联的各种属性
Sub BorderLineStyles()
Dim rg As Range
Set rg = ThisWorkbook.Worksheets("Borders").Range("LineStyleListStart").Offset(, ) Do Until IsEmpty(rg)
rg.Offset(, ).Borders(xlEdgeBottom).LineStyle = rg.Offset(, ).Value
Set rg = rg.Offset(, )
Loop Set rg = Nothing
End Sub
代码清单10.6:代码清单10.5的一个替代方法
Sub BorderLineStyles2()
Dim rg As Range
Set rg = ThisWorkbook.Worksheets("Borders").Range("LineStyleListStart") rg.Offset(, ).Borders(xlEdgeBottom).LineStyle = xlContinuous
rg.Offset(, ).Borders(xlEdgeBottom).LineStyle = xlDash
rg.Offset(, ).Borders(xlEdgeBottom).LineStyle = xlDashDot
rg.Offset(, ).Borders(xlEdgeBottom).LineStyle = xlDashDotDot
rg.Offset(, ).Borders(xlEdgeBottom).LineStyle = xlDot
rg.Offset(, ).Borders(xlEdgeBottom).LineStyle = xlDouble
rg.Offset(, ).Borders(xlEdgeBottom).LineStyle = xlLineStyleNone
rg.Offset(, ).Borders(xlEdgeBottom).LineStyle = xlSlantDashDot Set rg = Nothing
End Sub
expression.BorderAround(LineStyle, Weight, ColorIndex, Color, ThemeColor)
用于围绕范围创建一个边界。参见:http://msdn.microsoft.com/en-us/library/ff197210(v=office.15).aspx
10.1.5 格式化数字
NumberFormat属性是一个描述范围值如何输出的字符串。
在Excel帮助中搜索:创建或删除自定义数字格式,可以查看关于格式字符串的详细解释。
代码清单10.7:试验格式代码
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = Me.Range("FormatCode").Address Then
ApplyFormatCode
End If
End Sub
Private Sub ApplyFormatCode()
'if we attempt to apply an invalid
'number format code an error will
'occur - we need to catch it
On Error GoTo ErrHandler
'clear any prior invalid code message
Me.Range("FormatCode").Offset(, ).Value = ""
'attempt to apply the format code
Me.Range("TestFormatCode").NumberFormat = Me.Range("formatcode").Value
Exit Sub ErrHandler:
'OOPS-invalid format code
'set the format to general
Me.Range("TestFormatCode").NumberFormat = "General"
'let the user know what happened
Me.Range("FormatCode").Offset(, ).Value = "Invalid Format Code!" End Sub
10.1.6 缩放工作表时节省大量时间
下面演示通过修改NumberFormat来缩放数值的显示。
代码清单10.8:为报表提供动态缩放
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = Me.Range("ScaleFactor").Address Then
ScaleData
End If
End Sub Private Sub ScaleData()
If Me.Range("ScaleFactor").Value = "Normal" Then
Me.Range("ScaleRange").NumberFormat = "#,##0"
Else
Me.Range("scaleRange").NumberFormat = "#,"
End If
End Sub
10.2 图表操作
10.2.1 从头创建图表
代码清单10.9:使用ChartWizard方法创建一个新图表
'creates a chart using the ChartWizard Method
Sub CreateExampleChartVersionI()
Dim ws As Worksheet
Dim rgChartData As Range
Dim chrt As Chart Set ws = ThisWorkbook.Worksheets("Basic Chart")
Set rgChartData = ws.Range("B1").CurrentRegion 'create a new empty chart
Set chrt = Charts.Add 'embed chart in worksheet - this creates a new object
Set chrt = chrt.Location(xlLocationAsObject, ws.Name) 'use chart wizard to populate/format empty chart
chrt.ChartWizard _
Source:=rgChartData, _
Gallery:=xlColumn, _
Format:=, _
PlotBy:=xlColumns, _
categorylabels:=, _
serieslabels:=, _
HasLegend:=True, _
Title:="Gross Domestric Product Version I", _
Categorytitle:="year", _
valuetitle:="GDP in billions of $" Set chrt = Nothing
Set rgChartData = Nothing
Set ws = Nothing
End Sub
代码清单10.10:使用Chart对象创建一个图表
'creates a chart using basic chart properties and Methods
Sub CreateExampleChartVersionII()
Dim ws As Worksheet
Dim rgChartData As Range
Dim chrt As Chart Set ws = ThisWorkbook.Worksheets("Basic Chart")
Set rgChartData = ws.Range("B1").CurrentRegion 'create a new empty chart
Set chrt = Charts.Add 'embed chart in worksheet - this creates a new object
Set chrt = chrt.Location(xlLocationAsObject, ws.Name) With chrt
.SetSourceData rgChartData, xlColumns
.HasTitle = True
.ChartTitle.Caption = "Gross Domestric Product Version II"
.ChartType = xlConeColClustered With .Axes(xlCategory)
.HasTitle = True
.AxisTitle.Caption = "Year"
End With With .Axes(xlValue)
.HasTitle = True
.AxisTitle.Caption = "GDP in billions of $"
End With
End With Set chrt = Nothing
Set rgChartData = Nothing
Set ws = Nothing
End Sub
10.2.2 图表搜索
可以像工作表一样引用图表页
Dim chrt1 As Chart
Dim chrt2 As Chart 'set a reference to the chart sheet named Chart4
Set chrt1 = ThisWorkbook.Charts("Chart4") 'set a reference to the 2nd chart sheet in this workbook
Set chrt2 = ThisWorkbook.Charts()
如果图表嵌入在一个工作表中,我们需要使用ChartObjects集合。
Dim ws As Worksheet
Dim chrt1 As Chart
Dim chrt2 As Chart
Set ws = ThisWorkbook.Worksheets()
'set a reference to the embedded chart named Chart4
Set chrt1 = ws.ChartObjects("Chart4").Chart
'set a reference to the 2nd embedded chart
Set chrt2 = ws.ChartObjects().Chart
代码清单10.11:使用图表标题查寻图表
'searches charts on a worksheet by chart title
Function GetChartByCaption(ws As Worksheet, sCaption As String) As Chart
Dim cht As Chart
Dim chtObj As ChartObject
Dim sTitle As String Set cht = Nothing 'loop through all chart objects on the ws
For Each chtObj In ws.ChartObjects
'make sure current chart object chart has a title
If chtObj.Chart.HasTitle Then
sTitle = chtObj.Chart.ChartTitle.Caption
'is this title a match?
If StrComp(sTitle, sCaption, vbTextCompare) = Then
' bingo
Set cht = chtObj.Chart
Exit For
End If
End If
Next Set GetChartByCaption = cht Set chtObj = Nothing
Set cht = Nothing
End Function Sub TestGetChartByCaption()
Dim ws As Worksheet
Dim cht As Chart Set ws = ThisWorkbook.Worksheets("Basic Chart")
Set cht = GetChartByCaption(ws, "I am the Chart Title") If Not cht Is Nothing Then
MsgBox "Found chart"
Else
MsgBox "Sorry, Can not Found chart"
End If Set cht = Nothing
Set ws = Nothing
End Sub
代码清单10.12:格式化一个基本图表
Sub FormattingCharts()
Dim ws As Worksheet
Dim cht As Chart
Dim ax As Axis Set ws = ThisWorkbook.Worksheets("Basic Chart")
Set cht = GetChartByCaption(ws, "GDP") If Not cht Is Nothing Then
'Format category axis
Set ax = cht.Axes(xlCategory)
With ax
.AxisTitle.Font.Size =
.AxisTitle.Font.Color = vbRed
End With 'Format value axis
Set ax = cht.Axes(xlValue)
With ax
.HasMinorGridlines = True
.MinorGridlines.Border.LineStyle = xlDashDot
End With 'format plot area
With cht.PlotArea
.Border.LineStyle = xlDash
.Border.Color = vbRed
.Interior.Color = vbWhite
.Width = cht.PlotArea.Width +
.Height = cht.PlotArea.Height +
End With 'format misc other
cht.ChartArea.Interior.Color = vbWhite
cht.Legend.Position = xlLegendPositionBottom
End If Set ax = Nothing
Set cht = Nothing
Set ws = Nothing
End Sub
10 探索其他Excel对象的更多相关文章
- ASP.NET导出EXCEl方法使用EXCEl对象
导出功能必须使用 office中EXCEl对象,整个操作如同在操作EXCEl一样,建立EXCEl应用----建立工作簿---建立sheet表单页, 代码实现过程中,如果想对单元格实现一些操作,或者汇 ...
- ASP.NET导出EXCEl方法使用COM.EXCEL不使用EXCEl对象
第一种:导出gridVIEW中的数据,用hansTABLE做离线表,将数据库中指定表中的所有数据按GRIDVIEW中绑定的ID导出 只能导出数据不能去操作相应的EXCEl表格,不能对EXCEL中的数据 ...
- 个人永久性免费-Excel催化剂功能第56波-获取Excel对象属性相关自定义函数
之前零散开发过一些自定义函数获取Excel对象属性,此次再细细地把有价值的属性都一一给开发完成,某些场景下,有这些小函数还是可以比较方便地实现一些通过Excel界面没法轻松获取到的信息. 修复与更新 ...
- ADO对Excel对象进行连接时的 两种方法区别
在通过ADO对Excel对象进行连接时(此时Excel则认为是一个数据源),需要配置对Excel数据源对应的连接串,这个连接串中包括了Provider信息(其实类似对数据库进行连接操作时,都需要指定连 ...
- Excel VBA入门(五)Excel对象操作
本章是本系列教程的重点.但我觉得应该不是难点.从第零章开始到学完本章,应该可以把VBA用于实战中了. Excel对象主要有4个: 工作薄 Workbook 工作表 Worksheet 单元格区域 Ra ...
- C++对象的JSON序列化与反序列化探索续-复杂对象的序列化与反序列化
本文是基本上一篇博文进行改进而成,上一篇请见: C++对象的JSON序列化与反序列化探索 此处就不多说了,直接上代码. 1. 序列化基类 #pragma once #include <strin ...
- C# - 使用 OLEDB读取 excel(不用Excel对象).
参考: How to read from an Excel file using OLEDB 为了使用方便,我做成了工具类(OledbCommon.cs),好以后使用. 注:连接字符串中,Provid ...
- Python快速学习10: 循环的对象及设计 (生活的规律)
前言 系列文章:[传送门] 生活逐渐规律,按时睡觉.今天写博客,明天补时间看会书.慢慢的时间很珍惜 我很喜欢! 时钟就像个循环体,我们将它融入生活. 正文 循环对象的并不是随着Python的诞生就存在 ...
- 探索一个NSObject对象占用多少内存?
1 下面写代码测试探索NSObject的本质 Objective-C代码,底层实现其实都是C\C++代码 #import <Foundation/Foundation.h> int mai ...
随机推荐
- 2017 计蒜之道 初赛 第一场 A 阿里的新游戏
题链:https://nanti.jisuanke.com/t/15499 这题观察图纸可知成三线段上的相邻点之间的距离有1,2,3三种情况的,同时要成线段必然是同横坐标或者纵坐标,然后我们排除掉穿过 ...
- 基本dos
文件夹的操作: 进入指定盘符:盘符名+: dir:列出当前控制台下的所有文件以及文件夹 . cd +文件夹名称:进入指定文件夹 cd.. 返回上一级 cd \返回到当前目录的根目 ...
- CSS实现折叠面板
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...
- Python爬虫 爬取Web页面图片
从网页页面上批量下载jpg格式图片,并按照数字递增命名保存到指定的文件夹 Web地址:http://news.weather.com.cn/2017/12/2812347.shtml 打开网页,点击F ...
- 慕课笔记利用css进行布局【一列布局】
<html> <head> <title>一列布局</title> <style type="text/css"> bo ...
- poj 1330lca模板题离线算法
#include<iostream> #include<vector> using namespace std; const int MAX=10001; int pre[MA ...
- bzoj3545 Peaks 线段树合并
离线乱搞... 也就是一个线段树合并没什么 #include<algorithm> #include<iostream> #include<cstring> #in ...
- css3自定义流动条
<style> .item { height: 180px; overflow: auto; width: 180px; float: left; margin: 11px; box-sh ...
- P2910 [USACO08OPEN]寻宝之路Clear And Present Danger 洛谷
https://www.luogu.org/problem/show?pid=2910 题目描述 Farmer John is on a boat seeking fabled treasure on ...
- COGS2479(四维偏序)
题意:给定一个有n个元素的序列,元素编号为1~n,每个元素有三个属性a,b,c,求序列中满足i<j且ai<aj且bi<bj且ci<cj的数对(i,j)的个数. 分析:cdq分治 ...