vb常用代码

计算两个数的和

Dim num1 As Integer
Dim num2 As Integer
Dim sum As Integer

num1 = 5
num2 = 10
sum = num1 + num2

MsgBox "The sum is " & sum

循环输出数字

For i = 1 To 10
MsgBox i
Next i

判断条件并执行不同的操作

Dim num As Integer

num = 5

If num > 10 Then
MsgBox “The number is greater than 10”
ElseIf num < 10 Then
MsgBox “The number is less than 10”
Else
MsgBox “The number is equal to 10”
End If

创建数组并输出其中的元素

Dim arr(3) As String

arr(0) = “apple”
arr(1) = “banana”
arr(2) = “orange”
arr(3) = “grape”

For i = 0 To 3
MsgBox arr(i)
Next i

打开文件对话框并选择文件

Dim fileDialog As FileDialog
Set fileDialog = Application.FileDialog(msoFileDialogFilePicker)

fileDialog.AllowMultiSelect = False
fileDialog.Title = “Select a file”
fileDialog.Show

If fileDialog.SelectedItems.Count > 0 Then
MsgBox "You selected " & fileDialog.SelectedItems(1)
End If

创建函数并调用

Function AddNumbers(num1 As Integer, num2 As Integer) As Integer
AddNumbers = num1 + num2
End Function

Dim result As Integer

result = AddNumbers(5, 10)

MsgBox "The result is " & result

创建类并实例化

Class Person
Public Name As String
Public Age As Integer
End Class

Dim person1 As New Person
person1.Name = “John”
person1.Age = 30

Dim person2 As New Person
person2.Name = “Jane”
person2.Age = 25

MsgBox person1.Name & " is " & person1.Age & " years old."
MsgBox person2.Name & " is " & person2.Age & " years old."

创建窗体并添加控件

Public Sub CreateForm()
Dim frm As New UserForm
frm.Caption = “My Form”
frm.Width = 300
frm.Height = 200
frm.Show

Dim lbl As New Label
lbl.Caption = "Hello, World!"
lbl.Left = 50
lbl.Top = 50
lbl.Width = 200
lbl.Height = 20
frm.Controls.Add lbl

End Sub

打开Excel文件并读取数据

Dim xlApp As Excel.Application
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet

Set xlApp = CreateObject(“Excel.Application”)
Set xlBook = xlApp.Workbooks.Open(“C:\MyFile.xlsx”)
Set xlSheet = xlBook.Worksheets(“Sheet1”)

MsgBox xlSheet.Cells(1, 1).Value

xlBook.Close False
xlApp.Quit

创建数据库连接并执行查询

Dim conn As New ADODB.Connection
Dim rs As New ADODB.Recordset

conn.ConnectionString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\MyDatabase.accdb;”
conn.Open

rs.Open "SELECT * FROM Customers", conn

Do While Not rs.EOF
MsgBox rs(“Name”) & " - " & rs(“Email”)
rs.MoveNext
Loop

rs.Close
conn.Close"