1 VBA基本知识点
1.1 环境设置--EXCEL表配置
- EXCEL菜单里找开发工具,如果没有,则去EXCEL/文件/选项/自定义功能区/开发者工具/勾选 开发工具
- 打开的开放工具叫VBE,VB editor
- 并且开启宏设置,允许宏运行
- VBA相关 表格需要保存为.xlsm
1.2 不要求一定声明变量(但object 等必须先声明)
- 如果想严格声明: 必须声明变量
- 代码开头加 option explicit
- dim f1
- dim fso as object
- 如果是要object这种对象,必须先声明为object并,不能省略
1.3 VB与VBA
- 感觉VB不是那么OOP,
- 没看到class,没有从class里 new出来的实例 instance
- 但实际有 dim dict1 as dictionary, fso也是对象
- VBA是一种依附于,共生寄生在EXCEL的语言
- VB就是VBS
- VBA里的A就是 application,主要是指EXCEL,据说Word 和 PPT等也可以用VBA
- 我现在理解,VBA就是专用于excel的语言,里面专门为excel word写了很多对象
2 VBA 基本语法
2.1 基础坐标系 ( 与 EXCEL的 row-x column-y 是对应匹配的 )
- 虽然看起来奇怪,但是和EXCEL 的row ,column是匹配的,就好理解了
- 一般的坐标系是 x横轴,Y纵轴
- 但是VBA的坐标,明显是和EXCEL的 行,列对应的
2.2 过程(没有返回值,都返回"")
sub subName()
end sub
2.3 函数 (一定有返回值, 至少也会返回none,none空也算)
function fuctionName()
end function
2.4 分支结构if
- if then
- elseif then
- else
- endif
2.5 分支结构 select case
- select case m1
- case "A"
- case "B"
- case else
- endselect
2.6 for循环结构
- for each i in selection
- for i in 1 to 10 step 1
- for i = 1 to 5 step -2
2.7 do loop循环 和 while循环,以及do while,do until 变种
- 基础循环
- while ....wend
- do ... loop
- 变种
- do while .... loop 至少执行1次
- do .... loop while ....
- do until .... loop 至少执行1次
- do .... loop until ....
3 VBA里函数和过程的调用
- 直接调用函数名:functionname()
- call functionname() 也可以
- 应该没有 DOS里这种新开一个DOS窗口的,start functionname() 这种
4 和Bat,Python的一些相似点
4.1 VBA语法像BAT的地方
比如,有goto这种 跳转行,而不是跳转block,调用的写法。(不过VBA里也有调用其他函数,过程)
goto label
label:
另外和DOS不同的是: dos的goto语法 是 :在前面
goto label
:label
4.2 VBA像Python2的地方
- debug.print xxxx 或 debug.print (xxxx)
- msgbox xxxx 或 msgbox (xxxx)
- 前者是语句,后者是函数,VBA里两种写法都行
- VBA是需要调用返回值时,用函数写法。否则用语句得写法不要加括号
- 而py2里也是 print 或 print()都可以
- 但是py3就得规范为 print()这么写
Sub ponyma11()
Debug.Print "a"
Debug.Print ("b")
End Sub
5 VBA的一些注意点
5.1 字符串和变量名
- VBA中,只有"a" 才是字符串。而a 不是字符串是变量
- 没有返回值的 变量,语句,都返回空值,也就是0, false
Sub cs1()
a1 = 3
b1 = "3"
c1 = a3
d1 = a
Debug.Print Application.IsNumber(a1)
Debug.Print Application.IsNumber(b1)
Debug.Print Application.IsNumber(c1)
Debug.Print Application.IsNumber(d1)
Debug.Print
Debug.Print "a1=" & a1
Debug.Print "b1=" & b1
Debug.Print "c1=" & c1
Debug.Print "d1=" & d1
Debug.Print
Debug.Print IsNumeric(a1)
Debug.Print IsNumeric(b1)
Debug.Print IsNumeric(c1)
Debug.Print IsNumeric(d1)
Debug.Print
'看起来字符串必须引号"" 引起来
'或者是有些函数返回的,指定是字符串型
j1 = 3
k1 = "3"
l1 = "a3"
m1 = "a"
Debug.Print IsNumeric(3)
Debug.Print IsNumeric("3")
Debug.Print IsNumeric("a3")
Debug.Print IsNumeric("a")
Debug.Print
Debug.Print IsNumeric(j1)
Debug.Print IsNumeric(k1)
Debug.Print IsNumeric(l1)
Debug.Print IsNumeric(m1)
Debug.Print
End Sub