VBA基础
Access vba中with的作用与用法
2013-09-04 16:59:55
在vba代码中,我们常常看见with关键字,那么With 语句是用来对某个对象执行一系列的语句,而不用重复指出对象的名称。 用作于简化代码,可读性更高。看下面的示例: Private Sub cmdFor_Click() '一般的for语句循环     Dim ctl As Control     Dim i As Integer

    For i = 0 To Me.Controls.Count - 1         Set ctl = Me.Controls(i)         If TypeOf ctl Is CommandButton Then             ctl.FontSize = 10             ctl.Caption = "aa"         End If     Next End Sub

Private Sub cmdWith_Click() '利用with语句循环     Dim ctl As Control     Dim j As Integer

    For j = 0 To Me.Controls.Count - 1         Set ctl = Me(j)         If TypeOf ctl Is CommandButton Then             With ctl                 .FontSize = 9                 .Caption = "bb"             End With         End If     Next End Sub

注意 当程序一旦进入 With 块,object 就不能改变。因此不能用一个 With 语句来设置多个不同的对象