观察一下我们做合并工作表以及一些其它任务的VBA代码就会发现,我们经常能看到一些语句,例如:
if
end if
之类的固定语句,这些就是VBA中常用的基本语句。
这些语句可以实现循环、逻辑判断等等目的。VBA中的语句有70多种,今天我们学习最常用的四种语句中的第一种。
1、With语句
正常情况下我们完成下列需求:
选择单元格A1,设置字体加粗,倾斜,加下划线,底色为黄色。
代码如下:
Sub 宏1()
Range("A1").Font.Bold = True
Range("A1").Font.Italic = True
Range("A1").Font.Underline = xlUnderlineStyleSingle
Range("A1").Interior.Color = 65535
End Sub
对象.属性.属性值
这样,每个属性前面的对象都要重复写。
用with正好可以解决这个事情。
结构如下:
with 对象
.属性1=属性值
.属性2=属性值
.属性3=属性值
……
.属性N=属性值
end with
上面代码修改后如下:
Sub 宏2()
With Range("A1")
.Font.Bold = True
.Font.Italic = True
.Font.Underline = xlUnderlineStyleSingle
.Interior.Color = 65535
End With
End Sub
这样就可以避免每次都要重复写对象了。
转自:米宏Office