MK
摩柯社区 - 一个极简的技术知识社区
AI 面试

Visual Basic基础语法

2023-08-031.4k 阅读

变量与数据类型

在 Visual Basic 中,变量是用于存储数据的容器。每个变量都有一个数据类型,它决定了变量可以存储的数据种类以及占用的内存空间大小。

基本数据类型

  1. 数值型
    • 整数类型
      • Byte:字节型,占用1个字节,取值范围是 0 到 255。常用于存储无符号整数,例如表示颜色分量(0 - 255 表示 RGB 颜色值)。
      Dim b As Byte
      b = 100
      
      • Integer:整型,占用2个字节,取值范围是 - 32,768 到 32,767。适用于一般整数运算,比如计数等场景。
      Dim i As Integer
      i = 1000
      
      • Long:长整型,占用4个字节,取值范围是 - 2,147,483,648 到 2,147,483,647。当需要处理较大整数时使用,如处理文件大小(以字节为单位时可能数值较大)。
      Dim l As Long
      l = 1000000000
      
    • 浮点型
      • Single:单精度浮点型,占用4个字节,提供大约 7 位有效数字。用于需要一定精度但范围不是特别大的小数计算,如科学计算中的一般数据。
      Dim s As Single
      s = 3.14159
      
      • Double:双精度浮点型,占用8个字节,提供大约 15 到 17 位有效数字。适用于高精度的小数计算,如金融计算、复杂科学模拟等。
      Dim d As Double
      d = 3.14159265358979
      
  2. 字符型
    • String:字符串类型,用于存储文本。可以是固定长度或可变长度。
      • 可变长度字符串
      Dim str1 As String
      str1 = "Hello, World!"
      
      • 固定长度字符串:定义时指定长度,当实际内容不足指定长度时,用空格填充。
      Dim str2 As String * 10
      str2 = "Hello" '此时 str2 实际存储为 "Hello     "
      
  3. 布尔型
    • Boolean:布尔类型,占用2个字节,只有两个值:True 和 False。常用于逻辑判断,如条件语句中的判断条件。
    Dim isDone As Boolean
    isDone = True
    
  4. 日期型
    • Date:日期类型,占用8个字节,用于存储日期和时间。可以使用多种格式表示日期和时间,如 #mm/dd/yyyy hh:mm:ss#。
    Dim today As Date
    today = #10/01/2023 12:00:00#
    

变量声明

  1. 显式声明:在使用变量前明确声明其数据类型。这有助于提高代码的可读性和可维护性,同时可以避免一些类型不匹配的错误。
Dim num As Integer
Dim name As String
  1. 隐式声明:在 Visual Basic 中,如果没有开启强制声明(默认情况下未开启),可以不声明变量直接使用。但这种方式不推荐,因为可能会引入难以发现的错误。例如:
x = 10 '这里 x 未声明,默认是 Variant 类型

为了强制变量声明,可以在模块的开头加上 Option Explicit 语句。这样,任何未声明的变量在使用时都会导致编译错误。

常量

常量是在程序运行过程中值不会改变的量。在 Visual Basic 中,可以使用 Const 关键字来定义常量。

  1. 数值常量
Const PI As Double = 3.14159265358979
  1. 字符串常量
Const greeting As String = "Welcome to Visual Basic"

运算符与表达式

Visual Basic 提供了丰富的运算符,用于对数据进行各种操作。表达式是由运算符和操作数组成的计算式。

算术运算符

  1. 加法运算符(+):用于将两个数值相加,也可用于连接两个字符串。
Dim num1 As Integer, num2 As Integer, result As Integer
num1 = 5
num2 = 3
result = num1 + num2 'result 的值为 8

Dim str1 As String, str2 As String, combinedStr As String
str1 = "Hello"
str2 = " World"
combinedStr = str1 + str2 'combinedStr 的值为 "Hello World"
  1. 减法运算符(-):用于两个数值相减。
Dim num3 As Integer, num4 As Integer, difference As Integer
num3 = 10
num4 = 4
difference = num3 - num4 'difference 的值为 6
  1. 乘法运算符(*):用于两个数值相乘。
Dim num5 As Integer, num6 As Integer, product As Integer
num5 = 3
num6 = 7
product = num5 * num6 'product 的值为 21
  1. 除法运算符(/):执行常规除法,结果为浮点数。
Dim num7 As Double, num8 As Double, quotient As Double
num7 = 10
num8 = 3
quotient = num7 / num8 'quotient 的值约为 3.333333
  1. 整除运算符(\):执行整除运算,结果为整数,舍去小数部分。
Dim num9 As Integer, num10 As Integer, integerQuotient As Integer
num9 = 10
num10 = 3
integerQuotient = num9 \ num10 'integerQuotient 的值为 3
  1. 取模运算符(Mod):返回除法运算的余数。
Dim num11 As Integer, num12 As Integer, remainder As Integer
num11 = 10
num12 = 3
remainder = num11 Mod num12 'remainder 的值为 1
  1. 指数运算符(^):用于计算一个数的幂次方。
Dim base As Double, exponent As Double, power As Double
base = 2
exponent = 3
power = base ^ exponent 'power 的值为 8

比较运算符

  1. 等于运算符(=):用于比较两个值是否相等,返回布尔值。
Dim num13 As Integer, num14 As Integer
num13 = 5
num14 = 5
Dim isEqual As Boolean
isEqual = num13 = num14 'isEqual 的值为 True
  1. 不等于运算符(<>):判断两个值是否不相等。
Dim num15 As Integer, num16 As Integer
num15 = 10
num16 = 20
Dim isNotEqual As Boolean
isNotEqual = num15 <> num16 'isNotEqual 的值为 True
  1. 大于运算符(>):判断左边的值是否大于右边的值。
Dim num17 As Integer, num18 As Integer
num17 = 15
num18 = 10
Dim isGreater As Boolean
isGreater = num17 > num18 'isGreater 的值为 True
  1. 大于等于运算符(>=):判断左边的值是否大于或等于右边的值。
Dim num19 As Integer, num20 As Integer
num19 = 10
num20 = 10
Dim isGreaterOrEqual As Boolean
isGreaterOrEqual = num19 >= num20 'isGreaterOrEqual 的值为 True
  1. 小于运算符(<):判断左边的值是否小于右边的值。
Dim num21 As Integer, num22 As Integer
num21 = 5
num22 = 8
Dim isLess As Boolean
isLess = num21 < num22 'isLess 的值为 True
  1. 小于等于运算符(<=):判断左边的值是否小于或等于右边的值。
Dim num23 As Integer, num24 As Integer
num23 = 7
num24 = 7
Dim isLessOrEqual As Boolean
isLessOrEqual = num23 <= num24 'isLessOrEqual 的值为 True

逻辑运算符

  1. 逻辑与运算符(And):当两个操作数都为 True 时,结果为 True;否则为 False。
Dim condition1 As Boolean, condition2 As Boolean, result1 As Boolean
condition1 = True
condition2 = False
result1 = condition1 And condition2 'result1 的值为 False
  1. 逻辑或运算符(Or):只要两个操作数中有一个为 True,结果就为 True;只有当两个操作数都为 False 时,结果才为 False。
Dim condition3 As Boolean, condition4 As Boolean, result2 As Boolean
condition3 = True
condition4 = False
result2 = condition3 Or condition4 'result2 的值为 True
  1. 逻辑非运算符(Not):对操作数进行取反操作,True 变为 False,False 变为 True。
Dim condition5 As Boolean, result3 As Boolean
condition5 = True
result3 = Not condition5 'result3 的值为 False
  1. 逻辑异或运算符(Xor):当两个操作数不同时,结果为 True;当两个操作数相同时,结果为 False。
Dim condition6 As Boolean, condition7 As Boolean, result4 As Boolean
condition6 = True
condition7 = False
result4 = condition6 Xor condition7 'result4 的值为 True

字符串运算符

  1. 连接运算符(&):用于连接两个字符串,返回一个新的字符串。
Dim str3 As String, str4 As String, newStr As String
str3 = "Visual"
str4 = " Basic"
newStr = str3 & str4 'newStr 的值为 "Visual Basic"

运算符优先级

当一个表达式中包含多个运算符时,运算符的优先级决定了运算的顺序。优先级从高到低大致如下:

  1. 算术运算符:指数(^)、取负(-)、乘法和除法(*、/、\、Mod)、加法和减法(+、-)。
  2. 字符串连接运算符:&。
  3. 比较运算符:=、<>、>、>=、<、<=。
  4. 逻辑运算符:Not、And、Or、Xor。

例如,在表达式 3 + 2 * 4 ^ 2 中,先计算 4 ^ 2 = 16,然后 2 * 16 = 32,最后 3 + 32 = 35

控制结构

控制结构允许程序根据不同的条件执行不同的代码块,或者重复执行一段代码。

条件语句

  1. If...Then 语句:用于简单的条件判断。如果条件为 True,则执行 Then 后面的语句。
Dim num25 As Integer
num25 = 10
If num25 > 5 Then
    MsgBox "The number is greater than 5"
End If
  1. If...Then...Else 语句:当条件为 True 时执行 Then 后面的语句块,当条件为 False 时执行 Else 后面的语句块。
Dim num26 As Integer
num26 = 3
If num26 > 5 Then
    MsgBox "The number is greater than 5"
Else
    MsgBox "The number is less than or equal to 5"
End If
  1. If...Then...ElseIf...Else 语句:用于多条件判断。依次检查每个条件,当某个条件为 True 时,执行对应的语句块,然后跳过整个 If 语句。
Dim score As Integer
score = 75
If score >= 90 Then
    MsgBox "A"
ElseIf score >= 80 Then
    MsgBox "B"
ElseIf score >= 70 Then
    MsgBox "C"
ElseIf score >= 60 Then
    MsgBox "D"
Else
    MsgBox "F"
End If
  1. Select Case 语句:适用于对一个表达式进行多种不同值的判断。
Dim day As Integer
day = 3
Select Case day
    Case 1
        MsgBox "Monday"
    Case 2
        MsgBox "Tuesday"
    Case 3
        MsgBox "Wednesday"
    Case Else
        MsgBox "Other day"
End Select

循环语句

  1. For...Next 循环:用于已知循环次数的情况。
Dim i As Integer
For i = 1 To 5
    MsgBox "Iteration " & i
Next i

在这个例子中,变量 i 从 1 开始,每次循环增加 1,直到 i 大于 5 时停止循环。 2. For Each...Next 循环:用于遍历数组或集合中的每个元素。

Dim fruits() As String
fruits = Split("Apple, Banana, Orange", ", ")
Dim fruit As Variant
For Each fruit In fruits
    MsgBox fruit
Next fruit

这里通过 Split 函数将字符串分割成数组,然后使用 For Each...Next 循环遍历数组中的每个元素。 3. Do...Loop 循环:用于在条件满足或不满足时循环执行代码块。 - Do While...Loop:当条件为 True 时循环。

Dim count As Integer
count = 1
Do While count <= 3
    MsgBox "Count: " & count
    count = count + 1
Loop
- **Do Until...Loop**:当条件为 False 时循环。
Dim num27 As Integer
num27 = 10
Do Until num27 <= 0
    MsgBox "Number: " & num27
    num27 = num27 - 1
Loop
- **Do...Loop While**:先执行一次循环体,然后当条件为 True 时继续循环。
Dim value As Integer
value = 1
Do
    MsgBox "Value: " & value
    value = value + 1
Loop While value <= 3
- **Do...Loop Until**:先执行一次循环体,然后当条件为 False 时继续循环。
Dim num28 As Integer
num28 = 1
Do
    MsgBox "Number: " & num28
    num28 = num28 + 1
Loop Until num28 > 3

跳转语句

  1. Exit 语句:用于提前结束循环或过程。
    • Exit For:在 For...Next 循环中提前结束循环。
Dim j As Integer
For j = 1 To 10
    If j = 5 Then
        Exit For
    End If
    MsgBox "J: " & j
Next j
- **Exit Do**:在 `Do...Loop` 循环中提前结束循环。
Dim k As Integer
k = 1
Do
    If k = 3 Then
        Exit Do
    End If
    MsgBox "K: " & k
    k = k + 1
Loop
  1. GoTo 语句:无条件地将程序执行转移到指定的行号或标签处。虽然 GoTo 语句在某些情况下可以实现复杂的流程控制,但过度使用会使代码结构混乱,降低可读性,一般不推荐使用。
Dim num29 As Integer
num29 = 5
If num29 > 3 Then
    GoTo Label1
End If
MsgBox "Number is less than or equal to 3"
Label1:
MsgBox "Number is greater than 3"

数组

数组是一种数据结构,用于存储多个相同数据类型的元素。

一维数组

  1. 声明和初始化
Dim numbers(4) As Integer '声明一个包含 5 个元素(索引从 0 到 4)的整数数组
numbers(0) = 10
numbers(1) = 20
numbers(2) = 30
numbers(3) = 40
numbers(4) = 50

'或者使用数组字面量初始化
Dim fruits() As String = {"Apple", "Banana", "Orange"}
  1. 访问数组元素:通过索引访问数组中的元素,索引从 0 开始。
Dim num As Integer
num = numbers(2) 'num 的值为 30
Dim fruit As String
fruit = fruits(1) 'fruit 的值为 "Banana"

多维数组

  1. 二维数组:常用于表示矩阵或表格形式的数据。
Dim matrix(2, 3) As Integer '声明一个 3 行 4 列(行索引 0 - 2,列索引 0 - 3)的二维整数数组
matrix(0, 0) = 1
matrix(0, 1) = 2
matrix(0, 2) = 3
matrix(0, 3) = 4
matrix(1, 0) = 5
matrix(1, 1) = 6
matrix(1, 2) = 7
matrix(1, 3) = 8
matrix(2, 0) = 9
matrix(2, 1) = 10
matrix(2, 2) = 11
matrix(2, 3) = 12
  1. 遍历多维数组:可以使用嵌套的 For...Next 循环来遍历多维数组。
Dim i As Integer, j As Integer
For i = 0 To 2
    For j = 0 To 3
        MsgBox "matrix(" & i & ", " & j & ") = " & matrix(i, j)
    Next j
Next i

动态数组

动态数组的大小可以在程序运行时动态改变。

  1. 声明动态数组
Dim dynamicArray() As Integer '声明一个动态整数数组
  1. 调整动态数组大小:使用 ReDim 语句来调整动态数组的大小。
ReDim dynamicArray(4) '重新调整为包含 5 个元素
dynamicArray(0) = 1
dynamicArray(1) = 2
dynamicArray(2) = 3
dynamicArray(3) = 4
dynamicArray(4) = 5

'如果需要保留原有数据,可以使用 ReDim Preserve
ReDim Preserve dynamicArray(9) '重新调整为包含 10 个元素,原有数据保留

过程与函数

在 Visual Basic 中,过程和函数是将代码模块化的重要工具,有助于提高代码的可读性和可维护性。

子过程(Sub Procedure)

子过程是一段执行特定任务但不返回值的代码块。

  1. 定义子过程
Sub DisplayMessage()
    MsgBox "This is a sub - procedure"
End Sub
  1. 调用子过程
Call DisplayMessage '使用 Call 关键字调用
'或者直接调用
DisplayMessage

函数(Function Procedure)

函数是一段执行特定任务并返回一个值的代码块。

  1. 定义函数
Function AddNumbers(a As Integer, b As Integer) As Integer
    AddNumbers = a + b
End Function
  1. 调用函数
Dim result5 As Integer
result5 = AddNumbers(3, 5) 'result5 的值为 8

参数传递

  1. 按值传递(ByVal):默认情况下,参数是按值传递的。这意味着传递给过程或函数的是参数值的副本,在过程或函数中对参数的修改不会影响原始变量的值。
Sub ModifyValue(ByVal num As Integer)
    num = num + 10
End Sub

Dim originalNum As Integer
originalNum = 5
Call ModifyValue(originalNum)
MsgBox "Original number: " & originalNum '显示 5
  1. 按引用传递(ByRef):当参数按引用传递时,传递的是变量的内存地址,在过程或函数中对参数的修改会影响原始变量的值。
Sub ModifyValueByRef(ByRef num As Integer)
    num = num + 10
End Sub

Dim originalNum2 As Integer
originalNum2 = 5
Call ModifyValueByRef(originalNum2)
MsgBox "Original number: " & originalNum2 '显示 15

过程和函数的作用域

  1. 局部作用域:在过程或函数内部声明的变量具有局部作用域,只能在该过程或函数内部访问。
Sub LocalScopeExample()
    Dim localVar As Integer
    localVar = 10
    MsgBox "Local variable: " & localVar
End Sub
  1. 模块级作用域:在模块(如窗体模块或标准模块)中声明但在任何过程或函数外部的变量具有模块级作用域,可以被该模块中的所有过程和函数访问。
Dim moduleVar As Integer '模块级变量
Sub ModuleScopeExample1()
    moduleVar = 20
    MsgBox "Module variable in first sub: " & moduleVar
End Sub

Sub ModuleScopeExample2()
    MsgBox "Module variable in second sub: " & moduleVar
End Sub
  1. 全局作用域:在标准模块中使用 Public 关键字声明的变量具有全局作用域,可以被整个应用程序中的所有模块访问。
'在标准模块中
Public globalVar As Integer

'在窗体模块中
Sub GlobalScopeExample()
    globalVar = 30
    MsgBox "Global variable: " & globalVar
End Sub

面向对象编程基础

Visual Basic 支持面向对象编程(OOP),这使得代码更易于组织、维护和扩展。

类的定义

类是一种用户自定义的数据类型,它封装了数据(属性)和操作这些数据的方法。

  1. 定义简单类
Class Person
    Private m_name As String
    Private m_age As Integer

    Public Property Get Name() As String
        Name = m_name
    End Property

    Public Property Let Name(ByVal value As String)
        m_name = value
    End Property

    Public Property Get Age() As Integer
        Age = m_age
    End Property

    Public Property Let Age(ByVal value As Integer)
        m_age = value
    End Property

    Public Sub DisplayInfo()
        MsgBox "Name: " & m_name & ", Age: " & m_age
    End Sub
End Class

对象的创建和使用

  1. 创建对象实例
Dim person1 As New Person
person1.Name = "John"
person1.Age = 30
person1.DisplayInfo

继承

继承允许一个类(子类)从另一个类(父类)继承属性和方法,从而实现代码的复用。

  1. 定义父类
Class Animal
    Private m_name As String

    Public Property Get Name() As String
        Name = m_name
    End Property

    Public Property Let Name(ByVal value As String)
        m_name = value
    End Property

    Public Sub MakeSound()
        MsgBox "The animal makes a sound"
    End Sub
End Class
  1. 定义子类
Class Dog
    Inherits Animal

    Public Sub Bark()
        MsgBox "Woof!"
    End Sub
End Class
  1. 使用继承
Dim dog1 As New Dog
dog1.Name = "Buddy"
dog1.MakeSound '调用父类方法
dog1.Bark '调用子类特有的方法

多态

多态是指在继承体系中,不同的子类对象可以对相同的消息(方法调用)做出不同的响应。

  1. 重写父类方法:在子类中使用 Override 关键字重写父类的方法。
Class Cat
    Inherits Animal

    Public Overrides Sub MakeSound()
        MsgBox "Meow!"
    End Sub
End Class
  1. 多态的体现
Dim animal1 As Animal
Dim dog2 As New Dog
Dim cat1 As New Cat

animal1 = dog2
animal1.MakeSound '显示 "Woof!"

animal1 = cat1
animal1.MakeSound '显示 "Meow!"

通过以上对 Visual Basic 基础语法的详细介绍,你应该对 Visual Basic 编程有了较为全面的认识,可以开始编写各种功能丰富的 Visual Basic 程序。