全民一起VBA提高篇第一课:基本数据类型详解一

变体性能测试

Option Explicit

Sub test()

    Dim startTime
    startTime = Time()
    
    '请将i/j/a三个变量全部设置为变体并运行本程序,记下时间;
    '然后再将三者都设置为Integer并运行,再记下时间,并与前者比较。
    'Dim i, j, a
    Dim i As Integer, j As Integer, a As Integer
    '每次声明都要写完整,不然读不出
    '如果不申明,获取的是变体类型,太费内存了,执行效率也很低下
    For i = 1 To 20000
        For j = 1 To 20000
            a = 123
        Next j
    Next i
    MsgBox "共计运行 " & DateDiff("s", startTime, Time()) & " 秒"

End Sub

声明后用时是不申明的一半

数字类型

  1. integer %
  2. long &
  3. double # 支持小数
  4. currency @支持小数

两边都是数字字符串,用加号的作用相当于&
所以 连字符用的 &左右要留一个空格

Option Explicit
Sub 类型()
Dim a
'    a = 30000 * 2 '结果会溢出,因为30000 和2 默认为integer
'所以给30000*2后得到的结果,是要装入integer的,这里出现了溢出
a = 30000& * 2 '强制转为long
MsgBox a

End Sub

Option Explicit
Sub 类型()
Dim a
a = 30000& * 2: MsgBox a '冒号一用,可以拼在一行写

End Sub
Option Explicit
Sub 类型()
Dim a As Integer
Dim b As Integer
a = 11 / 3 '除号+四舍五入
b = 11 \ 3 '求余,去尾法
MsgBox a
MsgBox b
End Sub

日期函数

Option Explicit
Sub demo()
Dim d As Date
Dim a As Date
Dim b As Date
Dim c As Date

    d = #1/19/2019 12:20:25 PM# '设置时间类型的数据变量
    '用#号相当于字符串的""  顺序是 月日年
    a = Date    '   返回当前年月日
    b = Time() '这里多了括号 返回时分秒
    c = Now() '年月日 时分秒
    
    MsgBox d
    MsgBox a
    MsgBox b
    MsgBox c
    
End Sub

时间解析

year(d)
month(d)
day(d)
weekday(d)
hour(d)
minute(d)
second(d)

时间运算

Option Explicit
Sub demo()
Dim i As Long
i = 3

    Do While Trim(Cells(i, 2)) <> "" 'datediff函数用来算两个日期之间的差值
    Cells(i, 6) = DateDiff("w", Cells(i, 3), Cells(i, 4)) & "周"    'w对应周,d对应天数,s对应秒
    Cells(i, 7) = DateAdd("d", -400, Now()) 'dateadd,从现在起,往前推500天
    i = i + 1
    Loop
End Sub


日期型数据的本质是一个double类型的数字
0代表的是1899年12月30日0时0分0秒,整数部分每增减1就是增减1天,小数0.1代表0.1天,即2.4h或2小时24分钟

逻辑运算

ctrl+pause停止死循环

Option Explicit
Sub 交替上色()
Dim i As Long

Dim paint As Boolean        '定义bool变量

paint = False

i = 4

Do While Cells(i, 2) <> ""

    If Cells(i, 2) <> Cells(i - 1, 2) Then
        paint = Not paint
    End If
    
    If paint Then   '为bool变量才能这么改
        Range(Cells(i, 2), Cells(i, 4)).Interior.Color = RGB(255, 0, 0)
    End If
    
i = i + 1

Loop

End Sub

在这里插入图片描述

发布了26 篇原创文章 · 获赞 5 · 访问量 1100

猜你喜欢

转载自blog.csdn.net/qq_43568982/article/details/103775105
今日推荐