VBA中常用技巧

时间:2023-03-08 21:32:45

常量定义

Public Const i as Integer = 1

自定义类型

Type mytype

  i   as Integer

b  as  Boolean

s  as  String

end Type

错误处理

①跳过出错语句,继续执行

On Error Resume Next

处理代码

On Error Goto 0

②执行错误处理

On Error Resume Next

处理代码

On Error Goto ErrorHandler

ErrorHandler:

错误处理代码

分支处理

Select case condition

case "value1"

详细处理

case "value2"

详细处理

case  else

详细处理

End Select

循环处理

①For i = 1 to j (Step y)

详细处理

next i

②For each obj in objs

详细处理

next obj

③Do While / Until Condition

   详细处理

Loop

或Do

详细处理

Loop While / Until Condition

函数可选参数定义

Function funs(Optional i as Interger) as String

  详细处理

End Function

参数类型是Variant的场合,可用Ismissing(x)判断参数是否赋值

函数随机参数定义

Function funs(ParamArray arglist() as Variant) as Integer

End Function

函数有多个参数时,随机参数需定义在最后

变量显式定义

Option Explicit

所用变量必须事先定义,否则无效。一个好的变成习惯。

控件相关

①使用控件的MouseDown和MouseMove事件,实现在窗体内移动控件。

Private Sub Image1_MouseDown(Button, Shift, x, y)

  OldX = x

OldY = y

Image1.Zorder 0

End Sub

x,y是选中控件的鼠标坐标值,Zorder使该图像位于最前面。

Private Sub Image1_MouseMove(Button, Shift, x, y)

  If Button = 1 then

    Image1.Left = Image1.Left + (X - OldX)

    Image1.Top = Image1.Top + (Y - OldY)

  End if

End Sub

Button=1意味着按下了鼠标左键。