VISUAL BASIC实例源代码

合集下载

vb教程编程实例详解

vb教程编程实例详解

vb教程编程实例详解VB教程编程实例详解VB(Visual Basic)是一种面向对象的编程语言,它可以用于开发Windows应用程序。

在这里,我们将详细解释一些VB 编程实例,以帮助初学者更好地理解和掌握这门语言。

编程实例1:计算器首先,让我们创建一个计算器的VB程序。

我们将使用VB的窗体和按钮来实现这个功能。

首先,我们需要在窗体上添加一些按钮,如"1"、"2"、"+"、"="等。

然后,我们需要用一个文本框来显示计算结果。

在窗体上双击"+"按钮并添加以下代码:```Private Sub ButtonPlus_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ButtonPlus.ClickDim num1 As IntegerDim num2 As IntegerDim result As Integernum1 = Integer.Parse(TextBoxNum1.Text)num2 = Integer.Parse(TextBoxNum2.Text)result = num1 + num2TextBoxResult.Text = result.ToString()End Sub```在这个代码中,我们首先定义了三个变量:num1、num2和result,用于存储计算结果。

然后,我们使用Integer.Parse方法将文本框中输入的文本转换为整数类型,并将其赋值给num1和num2。

接下来,我们将num1和num2相加,将结果赋值给result,并使用result.ToString()方法将结果转换为字符串类型并显示在结果文本框中。

编程实例2:学生成绩管理系统接下来,让我们创建一个学生成绩管理系统的VB程序。

vb编程代码大全

vb编程代码大全

vb编程代码大全Visual Basic (VB) 是一种广泛用于软件开发的高级编程语言,可以用于开发 Windows 应用程序、Web 应用程序、数据库应用程序等。

在本文中,将介绍一些常用的 VB 编程代码,帮助初学者快速入门和提高编程水平。

一、基本数据类型1. 整型数据在 VB 中,整型数据可以使用 Integer 类型表示,范围为 -32,768 到32,767。

定义整型变量的代码如下:```Dim num As Integernum = 10```2. 浮点数据浮点数据可以使用 Single 或 Double 类型表示,分别表示单精度浮点数和双精度浮点数。

定义浮点变量的代码如下:```Dim num As Singlenum = 3.143. 字符串数据字符串数据可以使用 String 类型表示,可以存储文本数据。

定义字符串变量的代码如下:```Dim str As Stringstr = "Hello, World!"```二、控制流程1. If...Then...Else 语句If...Then...Else 语句用于根据条件执行不同的代码块。

例如:```Dim num As Integernum = 10If num > 0 ThenMsgBox("Num is positive.")ElseMsgBox("Num is negative.")End If2. For 循环For 循环用于重复执行一段代码。

例如:```For i = 1 To 10MsgBox(i)Next i```3. Do While 循环Do While 循环在满足条件时执行代码块。

例如:```Dim i As Integeri = 1Do While i <= 10MsgBox(i)i = i + 1Loop```三、数组1. 一维数组一维数组在 VB 中用于存储相同类型的多个元素。

Visual_Basic编程100例

Visual_Basic编程100例

在VB中播放AVI文件AVI文件是语音和影像同步组合在一起的文件格式。

在VB5?0中用MMControl多媒体控件设计播放AVI文件的程序步骤如下:1 新建一个工程。

2 在Form1上建立一个MMControl控件,并建立一个图片框。

3 设定MMControl对象的按钮属性。

4 撰写程序如下:Private Sub Form_Load()MMControl1.DeviceType=″avivideo″MMControl1.file name=″c:\vb\avi\a.avi″MMControl1.hWndDisplay=picture1.hWndmand=″Open″End Sub说明:1 DeviceType=″avivideo″,是设定MCI播放媒体的种类。

2 HwndDisplay=picture1.hWnd,是把AVI文件在图形框中播放,如果没有这一行,将自动开启一个窗口播放。

巧用VB编程使XMPLAYER自动播放VCD(缺少)用VB 5.0实现多画面播放功能2000-07-15· ·请作者与我们联系··学vb找王国荣font size=2>所谓动态画中画,指的是在大画面视频播放时,小画面在大画面中也播放另外的画面,或者是两个画面都在做某种活动。

笔者前段时间用VB 5.0开发了一个VCD播放程序,可以实现以下功能:(1)可以多屏播放,也就是画中画功能,可同时播放几个不同的画面;(2)可以同时播放CD-ROM中的视频音频文件(当然,在硬盘中播放速度会更快些);(3)支持多种文件格式(如.dat、.wav、.avi、.mov、.mmm、.mid、.rmi、.mpeg、.mpg、.mpa、.mpv等);(4)自带画面美观且功能齐全的CD播放程序;(5)增强了鼠标的右键功能,用它可以控制各画面的大小(1/16、1/4、1/2、1、2倍和全屏)、播放、暂停等;(6)控制声音、图像、时间/帧显示转换、自动重播等;(7)控制条随意拖动播放,再加上定时播放、自定义播放时间等播放方式,可使您更加惬意地控制VCD;(8)屏幕可随意拖动,画面可任意放缩。

visual basic程序设计项目化案例教程

visual basic程序设计项目化案例教程

visual basic程序设计项目化案例教程案例一:基于Visual Basic的大写字母转换小写字母的小程序本案例讲解如何使用Visual Basic设计一个小程序,将大写字母转换为小写字母。

一、介绍
Visual Basic是一种面向结构化编程环境,可以使程序员快速开发实用的应用程序,本例中使用Visual Basic设计一个小程序,能够实现大写字母转换为小写字母的功能。

二、开发流程
1、打开Visual Basic,启动开发环境。

2、新建文件保存为Project1,并设置主窗体。

3、拖入标题、文本框、按钮控件,使界面符合要求。

4、编写按钮的点击事件,实现将文本框中的大写字母转换为小写字母的功能。

5、运行程序,检查运行结果,是否符合要求。

三、代码实现
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Str as string
Str = TextBox1.Text
Str = Str.ToLower()
TextBox1.Text = Str
End Sub
四、测试
启动Visual Basic,运行本小程序,在文本框中输入大写字母,点击按钮后,文本框中的字母全部变成小写字母。

经测试,程序功能正常,能够按照要求实现功能。

五、小结
本案例主要讲述了如何使用Visual Basic进行资源的开发,实现将大写字母转换为小写字母的功能。

经测试,小程序功能正常,达到了预期效果。

visualbasic试验参考指导书程序代码

visualbasic试验参考指导书程序代码

VisualBasic试验参考指导书程序代码9-1Option ExplicitOption Base 1Private Sub Command1_Click(Dim x(10 As Integer, maxv As Integer, minv As Integer Dim i As IntegerFor i = 1 To 10x(i = Int(90 * Rnd + 10Text1.Text = Text1 & Str(x(iNext iCall maxmin(x, maxv, minvText2.Text = maxvText3.Text = minvEnd SubPrivate Sub Command2_Click(Text1.Text = ""Text2.Text = ""Text3.Text = ""End SubPrivate Sub Command3_Click(EndEnd SubPrivate Sub maxmin(a( As Integer, max As Integer, min As Integer Dim i As Integermax = a(1: min = a(1For i = LBound(a + 1 To UBound(aIf a(i > max Thenmax = a(iElseIf a(i < min Thenmin = a(iEnd IfNext iEnd Sub9-2Private Sub Command1_Click(Dim x As Longx = Val(Text1.TextIf verify(x ThenList1.AddItem xElseMsgBox Str(x & "不是自守数。

", vbInformation End If End SubPrivate Sub Command2_Click(Text1.Text = ""End SubPrivate Sub Command3_Click(EndEnd SubPrivate Function verify(x As Long As BooleanDim y As Long, s As Integerverify = Falses = Len(CStr(xy = x * xIf x = Val(Right(CStr(y, s Thenverify = TrueEnd IfEnd Function9-3Option ExplicitOption Base 1Private Sub Command1_Click(Dim a As Integer, b As Integer, i As Integera = Val(Text1.Text:b = Val(Text2.TextFor i = a To bIf sx(i = True ThenList1.AddItem i8 End IfNext iIf List1.ListCount = 0 Then List1.AddItem "无升序数" End Sub Private Sub Command2_Click(Text1.Text = ""Text2.Text = ""List1.ClearText1.SetFocusEnd SubPrivate Sub Command3_Click(EndEnd SubPrivate Function sx(ByVal n As Integer As Boolean Dim a( As Integer, k As Integer, i As IntegerDok = k + 1ReDim Preserve a(ka(k = n Mod 10n = n \ 10Loop Until n <= 0For i = 1 To UBound(a - 1If a(i + 1 >= a(i Then Exit FunctionNext isx = TrueEnd Function9-4Option ExplicitPrivate Sub Command1_Click(。

vb6.0开发实例

vb6.0开发实例

vb6.0开发实例Visual Basic 6.0(VB6.0)是一款经典的集成开发环境(IDE),用于Windows平台的软件开发。

本文将通过一个简单的实例来演示如何使用VB6.0创建一个学生成绩管理系统,旨在帮助初学者了解VB6.0的基本开发过程。

一、新建项目:打开VB6.0,选择“标准EXE”模板,创建一个新项目。

接下来,设计一个简单的窗体,包括学生姓名、学号、数学成绩和英语成绩等基本信息的输入框。

二、设计数据库:在VB6.0中,我们可以使用Access数据库作为后台数据库。

创建一个名为"StudentDB.mdb"的Access数据库,其中包含一个名为"StudentTable"的表,用于存储学生信息(姓名、学号、数学成绩、英语成绩)。

三、连接数据库:在VB6.0的窗体上添加ADO控件,用于与数据库进行交互。

通过ADO控件建立与"StudentDB.mdb"数据库的连接,并在代码中编写SQL语句,实现数据的插入、更新、删除和查询等操作。

' 连接数据库Private Sub Form_Load()Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Dat a Source="& App.Path & "\StudentDB.mdb;Persist Security Info=Fal se"Adodc1.RefreshEnd Sub四、添加按钮和事件处理:在窗体上添加按钮,如“添加记录”、“更新记录”、“删除记录”、“查询记录”等。

通过按钮的Click事件处理程序,调用相应的SQL语句实现对数据库的操作。

' 添加记录Private Sub cmdAdd_Click()Adodc1.Recordset.AddNewAdodc1.Recordset("Name") = txtName.TextAdodc1.Recordset("StudentID") = txtStudentID.TextAdodc1.Recordset("MathScore") = txtMathScore.TextAdodc1.Recordset("EnglishScore") = txtEnglishScore.TextAdodc1.Recordset.UpdateEnd Sub' 查询记录Private Sub cmdSearch_Click()Adodc1.RecordSource = "SELECT * FROM StudentTable WHERE StudentID = '"& txtSearchStudentID.Text & "'"Adodc1.RefreshEnd Sub' 更新记录Private Sub cmdUpdate_Click()Adodc1.Recordset("MathScore") = txtMathScore.TextAdodc1.Recordset("EnglishScore") = txtEnglishScore.TextAdodc1.Recordset.UpdateEnd Sub' 删除记录Private Sub cmdDelete_Click()Adodc1.Recordset.DeleteAdodc1.Recordset.UpdateEnd Sub五、界面美化:通过VB6.0提供的控件属性设置,对窗体和控件进行美化,使其更符合用户界面设计的要求。

40个Visual Basic 编程简单实例

40个Visual Basic 编程简单实例

目录实验题目1:设计窗体。

参考界面如下: (2)实验题目2: 设计一个计算器。

参考界面如下: (3)实验题目3:设计一个能够统计某学生三门课程成绩总分和平均分的程序。

参考界面如下: (4)实验题目4:设计界面,编写程序计算圆的周长和面积。

参考界面如下: (4)实验题目5:设计界面,编写程序验证算术运算符的功能。

参考界面如下: (5)实验题目6:设计界面,编写程序分离出一个三位数的个位、十位、百位上的数字。

参考界面如下: (6)实验题目7:输入一个三位数,将它按逆序输出。

参考界面如下: (7)实验题目8:输入两个数,将这两个数交换。

(8)实验题目9:设计文本编辑窗体。

(8)实验题目10:编写程序计算某个学生三门课程的平均成绩。

(10)实验题目12:编写程序计算长方体的体积。

(10)实验题目13:编写程序求出四个数中的最小数。

(11)实验题目14:编写程序判断某个数是否是水仙花数。

(11)实验题目15:编写程序,实现数字和英文单词的对应。

(12)实验题目16:设计程序,判断从键盘上输入的某个字符为哪类字符。

(大写字母、小写字母、数字字符或其他字符) (12)实验题目17:设计一个简单的文本编辑器,可以实现文本的简单格式化操作。

(13)实验题目18:编写程序输出图形,运行界面如下: (15)实验题目19:编写程序求n!。

(15)实验题目20:编写程序,求出某班所有同学某门课程的平均成绩。

(16)实验题目21:编写程序输出1-100之间所有能被3整除的整数,要求每行输出5个。

并输出这些整数的和。

(用for语句实现) (16)实验题目21:编写程序,统计输入的一个字符串中各类字符的个数。

(用for语句实现).17 实验题目22:编写程序,定义包含10个数组元素的一维数组,给该数组中的数组元素赋值为3,6,9,12......数字,并以顺序和逆序两种方式输出各元素值。

. (17)实验题目23:随机生成20个100以内的正整数,将其中的奇数和偶数分两行显示在窗体上,并分别统计奇数和偶数的个数。

vb数据库编程实例

vb数据库编程实例

vb数据库编程实例VB数据库编程实例:实现学生信息管理系统在计算机编程中,数据库是一项关键技术,用于有效地存储和管理数据。

VB(Visual Basic)是一种广泛使用的编程语言,可以轻松地与数据库进行交互。

本文将详细介绍如何使用VB进行数据库编程,以一个学生信息管理系统的实例为例。

第一步:建立数据库首先,我们需要建立一个数据库来存储学生的信息。

在本实例中,我们将使用Microsoft Access数据库。

打开Microsoft Access并创建一个新的数据库文件。

然后,创建一个新的数据表,其中列的字段如下:- 学生ID(StudentID):主键,唯一标识一个学生- 姓名(Name):学生的全名- 年龄(Age):学生的年龄- 专业(Major):学生所在的专业- 成绩(Grade):学生的总评成绩保存数据库并记录其路径,以便在VB中进行引用。

第二步:创建VB项目打开Visual Studio或任何其他VB开发环境,创建一个新的VB 项目。

命名为“学生信息管理系统”或其他适当的名称。

第三步:连接数据库在VB中连接数据库需要使用。

首先,我们需要导入System.Data和System.Data.OleDb命名空间。

然后,在VB代码中添加以下代码片段来连接到数据库:vbDim connStr As String ="Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<数据库路径>"Dim conn As New OleDbConnection(connStr)将`<数据库路径>`替换为第一步中保存的数据库文件路径。

第四步:加载学生信息接下来,我们将在VB中加载学生信息。

添加一个按钮控件到窗体上,并将其命名为“加载”。

然后,为该按钮的Click事件添加以下代码:vbPrivate Sub LoadButton_Click(sender As Object, e As EventArgs) Handles LoadButton.ClickDim selectQuery As String = "SELECT * FROM Students"Dim adapter As New OleDbDataAdapter(selectQuery, conn)Dim dataSet As New DataSet()adapter.Fill(dataSet, "Students")DataGridView1.DataSource =dataSet.T ables("Students")End Sub在此代码中,我们执行一个简单的查询,从数据库中检索所有学生的信息。

Visual Basic程序设计语言常用算法例题源代码30题

Visual Basic程序设计语言常用算法例题源代码30题

Visual Basic程序设计语言常用算法源代码30例题1、统计随机产生的十个两位正整数中偶数与奇数的个数,并求出偶数与奇数各自的总和Option ExplicitPrivate Sub Form_Click()Dim x As Integer, s1 As Integer, s2 As IntegerDim n1 As Integer, n2 As Integer, i As IntegerRandomizeFor i = 1 To 10_x=int(90*rnd)+10__Print x;If _ x mod 2=0 Thenn2 = n2 + 1s2 = s2 + xElse___n1=n1+1_s1 = s1 + xEnd IfNext iPrintPrint "奇数个数="; n1; "偶数个数="; n2;End Sub2.从字符串中分离数字和字母Private Sub Command1_Click()Dim s As String, i As IntegerConst ch As String = “0123456789.”s = "2L0A09U.0SI3V.24"For i = 1 To Len(s)If InStr(ch, Mid(s, i, 1)) = 0 Thenst1 = Mid(s, i, 1) & st1Elsest2 = st2 & Mid(s, i, 1)End IfNext iPrint st1: Print st2End Sub3. 统计字符串中“O”的个数Private Sub Command1_Click()a = "THERE IS A BOOK ON THE DESK"m = len(a)For i = 1 To mb =mid(a,i,1)If b = "O" Then num=num+1Next iPrint numEnd Sub4.从给定的字符串中只分离出数字Private Sub Command1_Click()Dim s As String, t As StringDim i As Integers = Text1.TextFor i = 1 To Len(s)If Mid(s, i, 1) >= "0" And Mid(s, i, 1) <= 9 Thent = t & Mid(s, i, 1)End IfNext iText2.Text = tEnd Sub5.(一)将正整数转化成二进制数Private Sub Command1_Click()Dim n As Long, t As Stringn = Val(Text1.Text)Dot = n Mod 2 & tn = n \ 2Loop Until n = 0Text2.Text = tEnd Sub5、(二)将正整数转化成16进制Private Sub Command1_Click()Dim n As Long, t As String, g As Stringn = Val(Text1.Text)Dog = n Mod 16If Val(g) > 9 Theng = Chr(55 + Val(g))End Ift = g & tn = n \ 16Loop Until n = 0Text2.Text = tEnd Sub5、(三)将正整数转化成8进制Private Sub Command1_Click()Dim n As Long, t As Stringn = Val(Text1.Text)Dot = n Mod 8 & tn = n \ 8Loop Until n = 0Text2.Text = tEnd Sub6.找出100以内的所有勾股数(不包括100)Private Sub Form_Click()Dim a As Integer, b As Integer, c As Integer, n As IntegerFor a = 1 To 99For b = 1 To 99For c = 1 To 99If a ^ 2 + b ^ 2 = c ^ 2 And a <> b Thenn = n + 1Print a; b; c; “; “;If n Mod 5 = 0 ThenPrintEnd IfEnd IfNext cNext bNext aPrint nEnd Sub7.找出三位数字中的所有升序数(各位数字>十位数字>百位数字)Private Sub Form_Click()Dim a As Integer, b As Integer, c As Integer, n As IntegerFor a = 1 To 9For b = 1 To 9For c = 1 To 9If a < b And b < c Thenn = n + 1Print a * 100 + b * 10 + c;If n Mod 10 = 0 Then '控制每行打印10个PrintEnd IfEnd IfNext cNext bNext aPrint nEnd Sub或Dim n As Integer, a1 As Integer, a2 As Integer, a3 As Integer, js As Integer For n = 100 To 999a1 = n \ 100 ‘取出百位数字a2 = n \ 10 Mod 10 ‘取出十位数字a3 = n Mod 10 ‘取出个位数字If a1 < a2 And a2 < a3 Thenjs = js + 1Print n;If js Mod 10 = 0 ThenPrintEnd IfEnd IfNext nPrint jsEnd Sub利用过程调用思想求升序数例找出a-b范围内的所有升序数,a>=100,b<=30000Private sub command1_click()Dim a as integer,b as integer,i as integera=text1:b=text2For i=a to bIf sx(i) thenList1.additem iEnd ifNext iEnd subPrivate sub function sx(byval n as integer) as booleanDim a() as integer,k as integer,i as integerDoK=k+1Redim preserve a(k)a(k)=n mod 10n=n\10loop until n<=0for i=1 to ubound(a)-1if a(i+1)>=a(i) then exit function (应该去判断a(1)>a(2)……a(k)但是不好判断,遇难则反,只要有一个a(i+1)>=a(i)这不是升序数)next isx=trueend function8.最小公倍数Private Sub Form_Click()Dim m%, n%, tem%m = Val(Text1.Text)n = Val(Text2.Text)tem = mDo While tem Mod n <> 0tem = tem + mLoopPrint m; "和"; n; "的最小公倍数是:"; temEnd Sub9.求一维数组a(n)各元素的和:Dim s as integer , I as intgers=0for i=1 to ns=s+a(i)next i10.求二维数组a(n,m)各元素的和Dim s as integer, i as integer, j as integers=0For i=1 to nfor j=1 to ms=s+a(i,j)next jNext i11. 求二维数组a(m,n)周边元素的和Dim s as integer, i as integerS=0For i=1 to ns=s+a(1,i)+a(m,i) (求第一行与最后一行的和)Next ifor i=2 to m-1s=s+a(i,1)+a(i,n) (求第二行到倒数第二行第一列与最后一列的和)Next i12、求二维数组a(n,n)主对角线元素的和(理解主对角线)Dim s as integer,i as integerS=0For i=1 to ns=s+ a (i,i)Next i13、求二维数组a(n,n)次对角线元素的Dim a as integer, i as integerS=0For i=1 to ns=s+a(i,n+1-i)Next i14、三种排序法(1)选择排序法是逐个比较,逆序交换;冒泡法是两两比较,逆序交换.(2)直接排序法(以降序为例)特点:比较后不立即互换元素,而是记下较大值的位置,并在每一轮比较完毕后和S(i)互换选择排序法(比较排序法)基本过程(以降序为例):将第一个元素顺序与其后面的元素比较,比第一个大则进行交换,第一轮完毕后,最大的元素被挪到了第一个位置,第二轮从第二个元素开始重复上面的过程,结束后得到第二个最大的元素,如此下去经过N-1 轮的比较,可将N 个数排好(3)冒泡法排序(以升序为例),则方法为:将相邻两个数比较,把小数对调到前边,如此进行一轮后,就会把最大的数互换到最后,再进行一次,则会把第二大数排在倒数第二的位置上,进行N-1次后,整个数列即可排好.在这种排序过程中,小数如同气泡一样逐层上浮,而大数逐个下沉,因此,被形象的喻为“冒泡”.选择法对数组经行降序排列Option explicitOption base 1Private sub command1_click()Dim sort(10) as integer, temp as integer , i as integer, j as integerFor i=1 to 10Sort(i)=int(rnd*99)+1Text1=text1 & str(sort(i))Next iFor i= 1 to 9For j=i+1 to 10If sort(i)<sort(j) thenTemp=a(i)a(i)=a(j)a(j)=tempend ifnext jtext2=text2 & str(sort(i))next itext2=text2 & str(sort(i))end sub直接排序法的精髓(降序)For i=1 to N-1pointer=I‘初始化pointer,在每轮比较开始处for j=I+1 to Nif Sort(pointer)< Sort(j) then pointer= j next jif I<> pointer thentemp=Sort(i) ‘交换Sort(i)=Sort(pointer)Sort(pointer)=tempend ifNext I冒泡排序法的精髓(升序)For i=1 to N-1for j=1 to N-i ‘比较次数逐次减少if S(j) > S(j+1) thent=S(j)S(j)=S(j+1)S(j+1)=t ‘立即互换end ifnext jnext i15、求三个数的和!Private Sub ifnum(str1 As String, n As Integer)Dim k As IntegerFor k = 1 To Len(str1) ‘逐个字符判断是否为数字If Asc(Mid(str1, k, 1)) < 48 Or Asc(Mid(str1, k, 1)) > 57 Thenn = 0: Exit SubEnd IfNext kn = 1End SubPrivate Sub Command1_Click()Dim a As String, b As String, c As StringDim y1 As Integer, y2 As Integer, y3 As Integera = Text1.Text ‘a,b,c用来取得三个文本框的字符串b = Text2.Textc = Text3.TextCall ifnum(a, y1) '用来判断a,b,c是否为数字串,为数字串时y1,y2,y3都为1 Call ifnum(b, y2)Call ifnum(c, y3)If y1 = 1 And y2 = 1 And y3 = 1 ThenText4.Text = Val(a) + Val(b) + Val(c)ElseText4.Text = "三个文本框内有非数字串"End IfEnd Sub16.求三个数的最小公倍数Option ExplicitPrivate Sub Command1_Click()Dim A As Integer, B As IntegerDim L As Long, C As IntegerA = Text1B = Text2C = Text3L = LCM(LCM(A, B), C)Text4 = LEnd SubPrivate Function LCM(ByVal X As Integer, ByVal Y As Integer)Dim M As Long, Flg As BooleanFlg = FalseDo Until FlgM = M + XIf M Mod Y = 0 ThenFlg = TrueEnd IfLoopLCM = MEnd Function17.打印九九乘法表Private sub form_clickDim I as integer, j as integerFor i=1 to 9For j=1 to iPrint j;”*”I;”=”i*j;Next jprintNext iEnd sub18判断完数(一个数如果恰好等于他所有因子之和,这个数就是完数。

visualbasic串口通信及编程实例

visualbasic串口通信及编程实例

visualbasic串口通信及编程实例Visual Basic串口通信及编程实例在实际的工业控制、机器人控制、智能家居等领域中,使用串口通信是一种非常广泛的方式。

Visual Basic (VB) 是一种微软公司开发的高级编程语言,它不仅易于学习,而且拥有丰富的图形界面设计和数据处理功能。

在本篇文章中,我们将深入介绍如何使用VB实现串口通信。

1. 建立串口通信首先,我们需要在VB中创建一个新的窗口(Form),然后打开工具箱,从中拖拽出一个SerialPort(串口)控件。

在控件属性中,我们需要为其指定相关的参数,例如串口名称、波特率、数据位、停止位、校验位等。

通常情况下,这些参数需要根据硬件设备的配置来进行调整。

在VB中实现串口通信的核心部分是对于SerialPort控件的事件监控。

具体来讲,当SerialPort收到一个数据包时,它会触发一个DataReceived事件。

对于这个事件,我们可以在程序中编写回调函数进行处理。

例如:Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e AsSystem.IO.Ports.SerialDataReceivedEventArgs) HandlesSerialPort1.DataReceived'在这里实现对于数据包的解析和处理End Sub2. 数据读取和发送在SerialPort控件中,有几种方法可以实现数据的读取和发送。

下面我们将介绍其中两种方法:(1) ReadExisting这个方法可以从串口中读取所有现有的数据,例如:Dim data As String = SerialPort1.ReadExisting()(2) Write这个方法可以向串口发送数据,例如:SerialPort1.Write("Hello World")注意,这个函数只能发送字符串数据。

vb编程代码大全

vb编程代码大全

vb编程代码大全VB(Visual Basic)是一种易于学习和使用的编程语言,广泛应用于Windows平台的软件开发。

VB编程通过编写和执行代码来实现任务,可以用于创建各种类型的应用程序,包括窗体应用程序、控制台应用程序、Web应用程序等。

本文将介绍一些常用的VB编程代码,帮助读者快速入门和掌握VB编程技巧。

一、VB基本语法在开始编写VB代码之前,我们先来了解一些基本的VB语法规则。

1. 注释VB中的注释用于解释代码的作用,不会被编译器执行。

注释可以是单行注释(以“'”开头)或多行注释(以“/*”开始,“*/”结束)。

示例:' 这是一个单行注释/*这是一个多行注释可以跨越多行*/2. 变量声明在VB中,变量需要先声明后使用。

变量的声明可以包括数据类型和变量名称。

示例:Dim x As Integer '声明一个整型变量x3. 变量赋值在VB中,可以使用赋值语句将一个值赋给变量。

示例:x = 10 '将变量x赋值为104. 运算符VB支持常见的运算符,包括算术运算符、比较运算符和逻辑运算符等。

示例:Dim a As Integer, b As Integera = 10b = 5Dim c As Integerc = a + b '加法运算c = a - b '减法运算c = a * b '乘法运算c = a / b '除法运算c = a Mod b '取余运算c = a > b '比较运算c = (a > 0) And (b > 0) '逻辑运算5. 控制结构VB中的控制结构包括条件语句和循环语句。

条件语句通过判断条件来选择不同的执行路径。

循环语句可以重复执行一段代码。

示例:If condition Then' 执行语句块1ElseIf condition2 Then' 执行语句块2Else' 执行语句块3End IfFor i = 1 To 10' 执行循环体Next i以上是VB的基本语法规则,通过掌握这些语法,可以编写简单的VB程序。

VisualBasic实例源代码

VisualBasic实例源代码

课前体验Private Sub Form_Click()For i = 1 To 10For j = 1 To iPrint "* ";Next jPrintNext iEnd Sub【例3-1】Private Sub Form_Click()c1$ = Chr$(13) + Chr$(10)msg1$ = "请输入您的名字: "msg2$ = "输入后按回车键"msg3$ = "或单击“确定”按钮"msg$ = msg1$ + c1$ + msg2$ + c1$ + msg3$name$ = InputBox(msg$, "InputBox 函数示例", "张三")Print name$End Sub【例3-2】Private Sub Form_Click()Msg1$=”Are you Continue to?”msg2$=”Operation Dialog Box”r=MsgBox(msg1$,34,msg2$)Print rEnd Sub【例3-3】编写程序,用MsgBox函数判断是否继续执行。

Private Sub Form_Click()msg$ = "请确认此数据是否正确"Title$ = "数据检查对话框"x = MsgBox(msg$, 19, Title$)If x = 6 ThenPrint x * xElseIf x = 7 ThenPrint "请重新输入"End IfEnd Sub【例3-5】Private Sub Form_Click()Print: PrintFontName = "隶书"FontSize = 16Print " 姓名"; Tab(8); "年龄"; Tab(16); "职务";Print Tab(24); "单位"; Tab(32); "籍贯"PrintPrint "吴大明"; Tab(8); 25; Tab(16); "职员"; Tab(24); "人事科"; Tab(32); "北京"End Sub【例3-6】Private Sub Form_Click()X = InputBox("请输入成绩", "学生成绩录入", "00")Print xEnd Sub【例3-7】Private Sub Form_Click()Dim x As Single, y As Singlex=InputBox(“请输入x的值”)If x>0 Then y=1 ElseIf x=0 Then y=0 Else y=-1Print “x=”; x ,”y=” ; yEnd Sub【例3-8】Private Sub Form_Click()Dim msg, UserInputmsg = "请输入一个字母或0~9之间的数字."UserInput = InputBox(msg) ‘输入一个字母或数字If Not IsNumeric(UserInput) Then ‘判断是否是数字If Len(UserInput) = 1 Then ‘不是数字时,判断输入的字符串长度是否为1Select Case Asc(UserInput) ‘判断输入字母的ASCII码值Case 60 To 90 '在60-90之间为大写字母msg = "你输入的是一个大写字母'"msg = msg & Chr(Asc(UserInput)) & "'。

VisualBasic技巧集锦(附示例源码)

VisualBasic技巧集锦(附示例源码)

VisualBasic技巧集锦(附示例源码)静态变量 iLeftOff 指定了字符长度。

自动选择 Te某t 的内容在使用VFP的应用进行录入时,每进入一个录入框,就自动选择该框中的所有内容。

利用以下的代码,也可实现类似的功能。

Private Sub MyTe某tBo某_GotFocus( AutoSelect MyTe某tBo某End SubSub AutoSelect(SelObject As Control) SelObject.SelStart = 0 If TypeOf SelObject Is MaskEdBo某 ThenSelObject.SelLength = Len(SelObject.FormattedTe某t) ElseIf TypeOf SelObject Is Te某tBo某 Then SelObject.SelLength = Len(SelObject.Te某t) End If End If End Sub捕捉 MouseE某it 事件MouseDown、MouseUp、MouseMove。

VB 似乎提供了很好的 Mouse 事件。

但好象还缺少什么!对!还差 MouseE某it(鼠标移出)事件。

在VB 中,我们要捕捉 MouseE某it 事件,必须用 API 函数:Private Declare Function SetCapture Lib \As LongPrivate Declare Function ReleaseCapture Lib \ 然后,我们可以在控件(以 Picture1 为例)的 MouseMove 事件上加上以下代码:Dim MouseE某it As BooleanMouseOver = (0 <= X) And (X <=\<=\........SetCapture Picture1.hWnd Else ........ReleaseCapture End If如何让文本框输入完后,直接跳入下一行?我们在编制程序的时候,特别是数据库软件,经常会遇到这样一个问题:在文本框中输入完后,用户习惯性的按下回车键。

【推荐】visualbasic范例-精选word文档 (16页)

【推荐】visualbasic范例-精选word文档 (16页)

本文部分内容来自网络整理,本司不为其真实性负责,如有异议或侵权请及时联系,本司将立即删除!== 本文为word格式,下载后可方便编辑和修改! ==visualbasic范例篇一:Visual+Basic实例源代码课前体验Private Sub Form_Click()For i = 1 To 10For j = 1 To iPrint "* ";Next jPrintNext iEnd Sub【例3-1】Private Sub Form_Click()c1$ = Chr$(13) + Chr$(10)msg1$ = "请输入您的名字: "msg2$ = "输入后按回车键"msg3$ = "或单击“确定”按钮"msg$ = msg1$ + c1$ + msg2$ + c1$ + msg3$name$ = InputBox(msg$, "InputBox 函数示例", "张三")Print name$End Sub【例3-2】Private Sub Form_Click()Msg1$=”Are you Continue to?”msg2$=”Operation Dialog Box”r=MsgBox(msg1$,34,msg2$)Print rEnd Sub【例3-3】编写程序,用MsgBox函数判断是否继续执行。

Private Sub Form_Click()msg$ = "请确认此数据是否正确"Title$ = "数据检查对话框"x = MsgBox(msg$, 19, Title$)If x = 6 ThenPrint x * xElseIf x = 7 ThenPrint "请重新输入"End IfEnd Sub【例3-5】Private Sub Form_Click()Print: PrintFontName = "隶书"FontSize = 16Print " 姓名"; Tab(8); "年龄"; Tab(16); "职务";Print Tab(24); "单位"; Tab(32); "籍贯"PrintPrint "吴大明"; Tab(8); 25; Tab(16); "职员"; Tab(24); "人事科";Tab(32); "北京"End Sub【例3-6】Private Sub Form_Click()X = InputBox("请输入成绩", "学生成绩录入", "00")Print xEnd Sub【例3-7】Private Sub Form_Click()Dim x As Single, y As Singlex=InputBox(“请输入x的值”)If x>0 Then y=1 ElseIf x=0 Then y=0 Else y=-1Print “x=”; x ,”y=” ; yEnd Sub【例3-8】Private Sub Form_Click()Dim msg, UserInputmsg = "请输入一个字母或0~9之间的数字."UserInput = InputBox(msg) ‘输入一个字母或数字 If NotIsNumeric(UserInput) Then ‘判断是否是数字If Len(UserInput) = 1 Then ‘不是数字时,判断输入的字符串长度是否为1Select Ca se Asc(UserInput) ‘判断输入字母的ASCII码值Case 60 To 90 '在60-90之间为大写字母msg = "你输入的是一个大写字母'"msg = msg & Chr(Asc(UserInput)) & "'。

应 用 实 例_Visual Basic程序设计_[共4页]

应 用 实 例_Visual Basic程序设计_[共4页]

202程序代码如下:Private Sub Dir1_Change() '使文件列表框和目录列表框同步File1.Pattern = "*.bmp;*.jpg;*.gif;*.ico" '指定文件列表中的文件类型File1.Path = Dir1.PathEnd SubPrivate Sub Drive1_Change() '使目录列表框和驱动器列表框同步Dir1.Path = Drive1.DriveEnd SubPrivate Sub File1_DblClick() '双击文件列表框事件If Right(File1.Path, 1) = "\" ThenFname = File1.Path & File1.FileNameElseFname = File1.Path & "\" & File1.FileNameEnd IfImage1.Picture = LoadPicture(Fname) '在图片控件中加载指定图片End Sub8.7 应 用 实 例例8.6 编写个人网购管理程序,可以通过该程序录入记录(包括商品名称、金额和购买时间),删除记录,显示记录,也可以通过时间段进行查询及统计消费总金额。

界面设计及程序运行结果如图8-9所示,各控件的属性设置如表8-4所示。

图8-9 网购管理程序表8-4 各控件的主要属性设置控件类别控件名属性属性值窗体Form1 Caption网购管理标签Label1-label6 按照图8-9自行设置TxtName Text 空白TxtMoney Text 空白TxtDay Text空白TxtS Text空白文本框TxtE Text空白。

Visual_Basic_实验指导书程序代码(精)

Visual_Basic_实验指导书程序代码(精)

Text3.Text =""9-1Option ExplicitOption Base 1Private Sub Comma nd1_Click(Dim x(10 As In teger, maxv As In teger, minv As In teger Dim i As In tegerFor i = 1 To 10x(i = In t(90 * Rnd + 10Text1.Text = Text1 & Str(x(iNext iCall maxmi n(x, maxv, minvText2.Text = maxvText3.Text = minvEnd SubPrivate Sub Comma nd2_Click(Text1.Text =""Text2.Text =""End SubPrivate Sub Comma nd3_Click(EndEnd SubPrivate Sub maxmin(a( As Integer, max As Integer, min As Integer Dim i As Integer max = a(1: min = a(1For i = LBou nd(a + 1 To UBou nd(aIf a(i > max The nmax = a(iElseIf a(i < min The nmin = a(iEnd IfNext iEnd Sub9-2Private Sub Comma nd1_Click(Dim x As Longx = Val(Text1.TextIf verify(x ThenList1.AddItem xElseMsgBox Str(x & ” 不是自守数。

",vbInformation End If End SubPrivate Sub Comma nd2_Click(Text1.Text =""End SubPrivate Sub Comma nd3_Click(EndEnd SubPrivate Function verify(x As Long As Boolea nDim y As Long, s As In tegerverify = Falses = Le n(CStr(xy = x * xIf x = Val(Right(CStr(y, s Thenverify = TrueEnd IfEnd Function9-3Option ExplicitOption Base 1Private Sub Comma nd1_Click(Dim a As In teger, b As In teger, i As In tegera = Val(Text1.Text:b = Val(Text2.TextFor i = a To bIf sx(i = True The nList1.Addltem i8 End IfNext iIf List1.ListCount = 0 Then List1.Addltem "无升序数"End Sub Private Sub Comma nd2_Click(Text1.Text =""Text2.Text =""List1.ClearText1.SetFocusEnd SubPrivate Sub Comma nd3_Click(EndEnd SubPrivate Function sx(ByVal n As Integer As Boolean Dim a( As Integer, k As Integer, i As In tegerDoReDim Preserve a(ka(k = n Mod 10n = n \ 10Loop Un til n <= 0For i = 1 To UBou nd(a - 1If a(i + 1 >= a(i Then Exit Function Next isx = TrueEnd Function9-4Option ExplicitPrivate Sub Comma nd1_Click(Text1.Text =""Text2.Text =""Text3.Text =""End SubPrivate Sub Comma nd2_Click(EndEnd SubPrivate Function common(ByVai a As Integer, ByVai b As Integer As Integer Dim r As In tegerDor = a Mod ba = bb = rLoop While r <> 0com mon = aEnd FunctionPrivate Sub Optio n1_Click(l ndex As In tegerDim a As In teger, b As In tegerDim m As In teger, d As In tegera = Textlb = Text2m = com mon(a, bIf In dex = 0 The nText3 = mElsed = a * b / mText3 = dEnd IfEnd Sub9-5Option ExplicitPrivate Function Judge( n As In teger As Boolea n Dim i As In tegerFor i = 2 To Sqr(nIf n Mod i = 0 Then Exit FunctionNext iJudge = TrueEnd FunctionPrivate Sub Comma nd1_Click(Text2.Text =""Dim x As In teger, i As In teger x = Textl.TextIf x = 4 The nText2 = "2+2"Elsei = 3Do While Text2 =""If Judge(i And Judge(x - i Then Text2 = i & "+" & x - iElsei = i + 2End IfLoopEnd IfEnd SubPrivate Sub Comma nd2_Click( Text1.Text =""End SubPrivate Sub Comma nd3_Click(EndEnd Sub9-6Private Function change(s As String, n As Integer As String Dim i As Integer, k As In teger, sum As In tegerDim p As Stri ng * 1, q As In tegerk = 0For i = Len( CStr(Text2.Text To 1 Step -1p = Mid(CStr(Text2.Text, i, 1If p >= "0" A nd p <= "9" Thenq = Val(pElseq = Asc(p - 55End Ifsum = sum + q * n A kk = k + 1Next icha nge = sumText2.Text =""End FunctionPrivate Sub Comma nd1_Click(Dim s As String, n As In tegerLabel2.Caption = Text1.Text & "进制数:" s = Text1.Text Select Case sCase 二"n = 2Case 八"n = 8Case十六"n = 16End SelectText3.Text = cha nge(s, nEnd SubPrivate Sub Comma nd2_Click(Textl.Text =""Text3.Text =""Text2.Text =""End SubPrivate Sub Comma nd3_Click( EndEnd Sub9-7Option ExplicitPrivate Sub Comma nd1_Click( Dim n As Longn = Text1.TextIf Right(CStr( n, 1 = "0" The n Text2 ="尾数为0,无反序数" ElseText2.Text = nx(nEnd IfEnd SubPrivate Sub Comma nd2_Click( Text1.Text =""End SubPrivate Sub Comma nd3_Click(EndEnd SubPrivate Function nx(n As Long As LongDim k As In teger, st As Stri ngDok = k + 1st = Mid(CStr( n, k, 1 & stLoop Until k >= Len (Text1.Textnx = Val(stEnd Function9-8Private Sub Comma nd1_Click(Dim n As Integer, i As Integer, s As String, a( As Integer For n = 153 To 9999If arm(n = True The nReDim a(Le n(CStr( nFor i = 1 To Len( CStr( na(i = Mid(CStr( n, i, 1Next iNext is =""For i = 1 To Len( CStr( n - 1s = s & CStr(a(i & "A" & CStr(Le n( CStr( n & "+"Next iListl.Addltem CStr(n & "=" & s & CStr(a(i & "A" & CStr(Len(CStr(n End If Next nEnd SubEndEnd SubPrivate Function arm(n As In teger As Boolea nDim a( As Integer, i As Integer, st As String, sum As Integerarm = Falsest = CStr( nReDim a(Le n(stFor i = 1 To Len(sta(i = Mid(st, i, 1For i = 1 To Len(stsum = Val(a(i A (Le n(st + sumNext iIf n = sum The narm = TrueElseExit FunctionEnd IfEnd Function9-9Dim sco(5 As Sin glePrivate Sub Comma nd1_Click(Dim i As In tegerFor i = 0 To 5sco(i = (I nt(R nd * 61 + 40 / 10Text1(i.Text = sco(iNext iEnd SubPrivate Sub Comma nd2_Click(Dim i As Integer, sum As Integer, min As Single, max As Single Call a(min, maxText1(i =""For i = 0 To 5sum = sum + sco(iNext iText7.Text = (sum - min - max / 4End SubPrivate Sub a(min As Single, max As Single Dim i As In teger, k As In tegermax = sco(0: min = sco(0For i = 1 To 5If sco(i > max The nmax = sco(iElseIf sco(i < min The nmin = sco(iEnd IfNext iEnd SubFor i = 0 To 5Next iText7.Text =""End SubPrivate Sub Comma nd4_Click( EndEnd Sub9-10Private Sub Comma nd1_Click( Dim max As Long, min As Long Call at(max, minText2.Text = maxText3.Text = minEnd SubPrivate Sub Comma nd2_Click( Text1.Text =""Text2.Text =""Text3.Text =""End SubPrivate Sub Comma nd3_Click( EndEnd SubPrivate Sub at(max As Long, min As LongDim s As Strin g, i As In teger, a( As In teger, k As In teger, temp As In teger, st As Stri ng, st1 As Stri ng s = CStr(Text1.TextReDim a(Le n(sFor i = 1 To Len(sk = k + 1a(k = Val(Mid(s, i, 1Next imax = a(1: min = a(1For i = 1 To Len(sFor j = 1 To Len(sIf a(i < a(j The ntemp = a(ia(i = a(ja(j = tempEnd IfNext jNext iIf a(1 = 0 The nFor i = 2 To Len(sIf a(i <> 0 Then Exit ForNext itemp = a(ia(i = a(1a(1 = tempEnd IfFor i = 1 To Len(s st = st & a(i Next imin = Val(stFor i = 1 To Len(sFor j = 1 To Len(sIf a(i > a(j The ntemp = a(ia(i = a(ja(j = tempEnd IfNext jNext iFor i = 1 To Len(sst1 = st1 & a(iNext imax = Val(st1End Sub7-2Option ExplicitOption Base 1Private Sub Comma nd1_Click(Dim a(20 As In teger, i As In teger, st As StringDim max As Integer, min As Integer, maxp As Integer, minp As Integer For i = 1 To 20a(i = In t(R nd * (100 - 1 + 1 + 1st = st & Str(a(iIf i Mod 10 = 0 Then st = st & vbCrLfNext iText1.Text = stmax = a(1: min = a(1maxp = 1: minp = 1For i = 2 To 20If a(i > max The nmax = a(imaxp = iElself a(i < min The nmin = a(imi np = iEnd IfNext iText2.Text = max & ” 位置是” & maxpText3.Text = min & ” 位置是” & minp End Sub Private Sub Comma nd2_Click(Text1.Text =""Text2.Text = "": Text3.Text =""End SubPrivate Sub Comma nd3_Click(EndEnd Sub7-5Private Sub cmdExit_Click(Un load MeEnd SubPrivate Sub cmdJudge_Click(Dim m As In teger, i As In teger, j As In teger, sum As In teger Dim a( m = Text1.Text For i = 1 To m / 2If m Mod i = 0 Thensum = sum + ij = j + 1ReDim Preserve a(ja(j = iEnd IfNext iIf m = sum The nPicture1.Print m & "是完数,因为"Picturel.Print m;"=";For i = 1 To UBou nd(a - 1Picturel.Pri nt a(i; "+";Next iPicturel.Pri nt a(iElsePicture1.Print m & " 不是元数"End IfEnd SubPrivate Sub cmdNext_Click(Picture1.ClsText1.Text =""Text1.SetFocusEnd Sub7-6Option ExplicitOption Base 1Private Sub Comma nd1_Click(Dim fn( As In teger, i As In teger, k As In tegerNext iDim j As In teger, st As String For i = 10 To 50k = 0Forj = 1 To i- 1If i Mod j = 0 Then k = k + 1 ReDim Preserve fn(kfn(k = jEnd IfNext jIf UBo und(fn = 3 The nst = i & ":"For j = 1 To UBound(fn - 1st = st & fn(j & ","Next jList1.Addltem st & fn(jEnd IfEnd SubPrivate Sub Comma nd2_Click(Listl.ClearEnd Sub7-7Private Sub Comma nd1_Click(Dim word( As Stri ng, S As Stri ngDim n As Integer, k As Integer, maxw As String S = Text1.Text Don = In Str(S,""If n <> 0 The nk = k + 1ReDim Preserve word(kword(k = Left(S, n - 1List1.Addltem word(kS = Right(S, Le n(S - nEnd IfLoop Un til n = 0ReDim Preserve word(k + 1word(k + 1 = Left(S, Len(S - 1Listl.Addltem word(k + 1maxw = word(k + 1For n = 2 To UBo un d(wordIf Len( word( n > Len( maxw The nmaxw = word(nEnd IfNext nText2.Text = maxwEnd SubPrivate Sub Comma nd2_Click(Text1.Text =""Text2.Text =""List1.ClearText1.SetFocusEnd SubPrivate Sub Command3_Click( End End Sub 7-9 Option Base 1 Private Sub Comma nd1_Click( Dim rn dArray(10 As In teger Dim i As In teger, j As In teger, temp As Integer Randomize Picture1.Print 排序前:"For i = 1 To 10 rndArray(i = Int(90 * Rnd + 10 Picture1.Print rndArray(i; Next i For i = 1 To 9 For j = 1 To 9 If rndArray(j > rndArray(j + 1 The n temp = rndArray(j rndArray(j = rndArray(j + 1: rndArray(j + 1 = temp End If Next jNext i Picturel.Print Picturel.Print "排序后:"For i = 1 To 10Picturel.Pri nt rndArray(i; Next i Picture1.Pri nt End Sub Private SubComma nd2_Click( Picture1.Cls End Sub Private Sub Comma nd3_Click( End End Sub。

Visual Basic上机考试题(双号)的源代码

Visual Basic上机考试题(双号)的源代码

V isual Basic 上机考试题双号试题的源代码第一种代码Private Sub Command1_Click()Label4.Caption = Text1.Text & "," & IIf(Option1.V alue, Option1.Caption, Option2.Caption) & "," & IIf(Option3.V alue, Option3.Caption, Option4.Caption) & "," & IIf(Check1.V alue = 1, _ "喜欢钓鱼", "") & "," & IIf(Check2.V alue = 1, _"下棋", "") & "," & IIf(Check3.V alue = 1, _"读书", "") & "," & IIf(Check4.V alue = 1, _"打球", "")End Sub第二种代码Private Sub Command1_Click()Dim n As String, m As String, b As String, s As String, a As String, c As String, d As StringIf Option1.V alue = True Thenn = Option1.CaptionElseIf Option2.V alue = True Thenn = Option2.CaptionEnd IfLabel4.Caption = nIf Option3.V alue = True Thenm = Option3.CaptionElseIf Option4.V alue = True Thenm = Option4.CaptionEnd Ifb = Text1.TextIf Check1.V alue = 1 Thens = Check1.CaptionElses = ""End IfIf Check2.V alue = 1 Thena = Check2.CaptionElsea = ""End IfIf Check3.V alue = 1 Thenc = Check3.CaptionElsec = ""End IfIf Check4.V alue = 1 Thend = Check4.CaptionElsed = ""End IfLabel4.Caption = b & "," & n & "," & m & "," & "喜欢:" & s & " " & a & " " & c & " " & dEnd Sub。

用实例学习Vsisual Basic 高级编程

用实例学习Vsisual Basic 高级编程

1.建立数据库的通用函数Sub createdatabase(databasename As String)Dim defaultworkspace As WorkspaceDim currentdatabase As Database,mydatabase As DatabaseSet defultworkspace=DBEngine.Workspace(0)Set mydatabase=defaultworkspace.createdatabase(databasename, dbLangGeneral)mydatabase.CloseEnd Sub2.建立数据表的通用函数Sub createtab(databasename As String, tablename As String.fldnametype()As String,_fldnamelength() As Integer)Dim i As IntegerDim mytabledef As TableDef, myfield As FieldDim mydatabase As Databasecaluculate_tbnumsFor j%=0 To table_num-1If mystr(j)="操作员注册表"ThenGo to MyendEnd IfNext j'Set mydatabase =Workspaces(0).OpenDatabase(databasename)Set mytabledef =mydatabase.Create TableDef(tablename)For i =1 To fldnamenoIf fldnametype(i)="1"ThenSet myfield=mytabledef.CreateField(fldname(i),dbInteger,fldnamelength(i))End ifIf fldnametype(i)="2"ThenSet myfield=mytabledef.CreateField(fldname(i),dblong,fldnamelength(i)) End IfIf fldnametype(i)="3"ThenSet myfield=mytabledef.CreateField(fldname(i),dbsingle, fldnamelength(i))End IfIf fldnametype(i)="4"ThenSet myfield=mytabledef.CreateField(fldname(i),dbText, fldnamelength(i))End IfIf fldnametype(i)="5"ThenSet myfield =mytabledef.CreateField(fldname(i),dbDate, fldnamelength(i))End Ifmytabledef.Fields.Append myfieldNext imydatabase.TableDefs.Append mytabledef Myend:End sub’求解数据表个数并赋值---calulate_tbnums()函数'Dim mystr() As String'Dim table_num As IntegerSub calculate_tbnums()Dim dbn As DatabaseDim td As TableDefsDim single_td As TableDef'Dim err_flag As IntegerDim mystr0() As stringDim ls_mystr() As string'Set dbn=OpenDatabase(statedb_path_dir)Set td =dbn.TableDefserr_flag=0For Each single_td In dbn.TableDefserr_flag=err_flag+1Next single_td'ReDim mystr0(err_flag) As String For i%=0 To err_flag-1Mystr0(i)=td(i).NameNext idbn.Close'j%=err_flagReDim ls_mystr(j) As Stringtable_num=0For i%=0 To j-1If mystr0(i)="操作员注册表"Then ls_mystr(i)=mystr0(i)table_num=table_num+1End IfNext i'ReDim mystr(table_num) As String i%=0For k%=0 To j-1If ls_mystr(k) <>""Thenmystr(i)=ls_mystr(k)i=i+1End IfNext kEnd Sub3.添加记录的通用函数Sub addrecords(databasename As String,tablename As String,_fldval() As Variant)Dim i As IntegerDim mydb As Database, mytable As RecordsetSet mydb=Workspace(0).OpenDatabase(databasename)Set mytable=mydb.OpenRecordset(tablename,dbOpenDynaset) mytable.AddNewFor i =1 To fldnamenomytable(fldname(i))=fldval(i)Next imytable .Updatemytable.closemydb.CloseEnd Sub建立操作员‚注册表数据库‛Private Sub Establish_registerdb()Dim db_path As StringDim mydb_name As StringDim db_name As StringDim dirname As String'mydb_name=‚临时文件目录‛db_path="c:\My_user"&"\"& mydb_nameIf Dir(db_path,vbDirectory)="临时文件目录"ThenGo To ml2End IfIf Dir("c:\My_user",vbDirectory)="My_user"ThenGo To ml0End IfMkDir"c:\My_user"'ml0:If Dir("c:\My_user"&"\"& mydb_name ,vbDirectory)= mydb_name Then Go To ml2End IfMkDir"c:\My_user"&"\"& mydb_nameml2:db_path_name=& db_path&"\"&"注册表数据库"'dirname=Dir(db_path&"\",vbDirectory)Do While dirname<>""If dirname="注册表数据库.mdb"ThenGo To myjumpEnd Ifdirname=DirLoopcreatedatabase db_path_namemyjump:End Sub2.建立‚操作员注册表‛Private Sub Establish_regtable()Dim db_tablename As StringDim fldnametype() As StringDim fldnamelength() As Integer'Statedb_path_dir="c:\My_user\临时文件目录\注册表数据库"db_tablename="操作员注册表"statedb_tbname=db_tablename '求解数据表时需要使用的全局变量'fldnameno=5Redim fldname(fldnameno) As StringRedim fldnametype (fldnameno) As StringRedim fldnamelength(fldnameno) As Integerfldname(1)="操作员代码"fldname(2)="操作员姓名"fldname(3)="注册时间"fldname(4)="操作员密码"fldname(5)="备注"fldnametype (1)="4"fldnamelength (1)=10fldnametype (2)="4"fldnamelength(2)=10fldnametype (3)="4"fldnamelength (3)=10fldnametype (4)="4"fldnamelength (4)=10fldnametype (5)="4"fldnamelength (5)=30createtab statedb_path_dir,db_tablename, fldnametype(),fldnamelength() End Sub3. 给‚操作员注册表‛添加记录Sub Regtable_CSH()Dim mydb As Database,mytable As RecordsetDim i As Integer'Statedb_path_dir="c:\My_user\临时文件目录\注册表数据库"Statedb_tbname="操作员注册表"Set mydb=Workspaces(0).OpenDatebase(statedb_path_dir)Set mytable=mydb.OpenRecordset(statedb_tbname,dbOpenDynaset) rdcount%=mytable.RecordCountIf rdcount>0 ThenGO to mytopEnd IfFor i=1 To 20ReDim fldnameval(5)As VariantIf i<=9 Thenfldnameval(1)="FFAHOMC-0"&i&""ElseFldnameval(1)="FFAHOMC-"&i""End Ifaddrecords statedb_path_dir, statedb_tbname, fldnameval()Next iMystop:End Sub三. 建立数据表和添加记录时在模块中定义的全局变量Dim statedb_path_dir As String ‘建表时用到的数据库路径,在相关模块中赋值Dim statedb_tbname As String ‘添加记录时需要打开的数据表名,在相关模块中赋值‘以上两个变量可以定义成模块全局变量,在相关模块中赋值,也可以在使用的地方直接用字符串形式给出‘以下变量在调用通用函数建库建表时必须定义成模块全局变量Dim mystr() As String‘数据表赋值数组Dim table_num As Integer ‘求解数据表个数变量'Dim fldname() As String ‘建表时用到的全局变量名Dim fldnameno As Integer ‘字段个数--建表和添加记录时用到的全局变量Dim fldnameval() As Variant ‘添加记录时用到的全局变量练习2---编写用户注册程序Dim statedb_path_dir As StringDim statedb_tbname As StringPrivate Sub Form_Load()Dim sSQL As StringMSFlexGrid 了.ColWidth(0)=1200MSFlexGrid 了.ColWidth(1)=1300MSFlexGrid 了.ColWidth(2)=1300MSFlexGrid 了.ColWidth(3)=1200MSFlexGrid 了.ColWidth(4)=1500'statedb_path_dir=‚c:\My_user\临时文件目录、注册表数据库‛statedb_tbname=‚操作员注册表‛'Ssql=‚SELECT*FROM‛&statedb_tbname&‛ORDER BY TRIM(操作员代码)ASC‛Data 1. databasename=statedb_path_dirData 1.RecordSource=SsqlData 1.RefreshEnd Sub'建立列表内容和文本框的联系Private Sub MSFlexGrid 1_Click ()MSFlexGri 1.Col=0opcode_lb.Csption=MSFlexGrid 1.TextMSFlexGri 1.Col=1opname_txt.Txt=MSFlexGrid 1.TextMSFlexGri 1.Col=2opregtime_txt.Text= MSFlexGrid 1.TextMSFlexGri 1.Col=3opkey_txt.Text= MSFlexGrid 1.TextMSFlexGri 1.Col=4opnote_txt.Text= MSFlexGrid 1.TextEnd Sub'操作员注册Private Sub regist_cmd_Click()User_registEnd SubPrivate Sub user_regist()Dim mydb As Database,mytable As Recordset'On Error GoTo MylastExitSet mydb=Workspaces(0).OpenDatabase(statedb_path_dir)Set mytable=mydb.OpenRecordset(statedb_tbname,dbOpenDynaset) DoWhile Not mytable.EOFIf mytable!操作员代码=Trim$(opcode_lb.Caption)Then‘mytable.操作员代码Mytable.EditIf Trim$(opname_txt.Text)<>‛‛Thenmytable!操作员姓名=Trim$(opname_txt.Text)End IfIf Trim$(opregtime_txt.Text)<>‛‛Thenmytable!注册时间=Trim$(opregtime_txt.Text)End IfIf Trim$(opkey_txt.Text)<>‛‛Then mytable!操作员密码=Trim$(opkey_txt.Text) End IfIf Trim$(opnote_txt.Text)<>‛‛Then mytable!备注=Trim$(opnote_txt.Text) End Ifmytable.UpdateEnd Ifmytable.MoveNextLoopmytable.Closemydb. CloseData1.RefreshMylastExit:End SubPrivate Sub close_cmd_Click()Unload MeEnd Sub练习3---编写用户注册程序Dim userpassword As StringDim mypath_dbname As StringDim mytbname As StringDim ComUserKey As StringPrivate Sub Form_load()Int_UserCodeListEnd SubPrivate Sub user_keyword_GotFocus()user_keyword.Text=‛‛End SubPrivate Sub ok_cmd_Click()Dim mydb As Database,mytable As RecordsetDim myTemp As VariantSet mydb=Workspaces(0).OpenDatabase(mypath_dbname)Set mytable= mydb..OpenRecordset(mytbname,dbOpenDynast) myTemp=‛‛Do While Not mytable.EOFIf mytable!操作员代码=ComUserKey And Not (IsNull(mytable!操作员密码))Then ‘mytable.操作员代码mytable.MoveNextLoopIf userpassword=myTemp ThenWorker_code=ComUserKey‘frm_主工作窗口.ctButton5.Enabled=Ture‘frm_主工作窗口.ctButton3.Enabled=Ture‘frm_主工作窗口.ctButton4.Enabled=Ture‘frm_主工作窗口.ctButton9.Enabled=Tureuserpassword=‛‛Unload frm_操作员登录frm_主工作窗口.ShowElseMsgBox‛口冷有误,请重新登录!‛,vbExclamation,‛系统信息‛userpassword=‛‛user_keyword.SetForcusEnd IfEnd SubPrivate Sub Int_UserCodeList()Dim mydb As Database,mytable As RecordsetDim usernum As Integermypath_dbname=‛c:\My_user\临时文件目录\注册表数据库.mdb‛mytbname=‛操作员表‛Set mydb=Workspace(0).OpenDatabase(mypath_dbname)Set mytable=mydb.OpenRecordset(mytbname,dbOpenDynaset)usernum=0usercode_list.ClearDo While Not mytable.EOFIf mytable!操作员姓名<>And Not(IsNull(mytable!操作员姓名)Then’mytable. 操作员姓名usercode_list.AddItem mytable! 操作员代码usernum%= usernum+1End Ifmytable.MoveNextLoopmytable.Closemydb.CloseIf usernum<> 0Thenusercode_list.LisIndex=0End IfEnd SubPrivate Sub usercode_list_Click()ComUserKey=usercode_list.TextEnd SubPrivate Sub user_keyword_KeyPress(KeyAscii As Integer)If KeyAscii=8 ThenIf Len(userpassword)>0 Then userpassword=Leftpassword,Len(userpaaword)-1 Elseuserpassword=‛‛End IfElseuserpassword= userpassword & Chr(KeyAscii) KeyAscii=Asc(‚*‛)End IfEnd SubPrivate Sub cancel_cmd_Click()Unload frm_操作员登录End Sub练习4:系统用户管理Dim mypath_dbname As StringDim mytbname As StringDim myCode Temp As StringDim Keyword_Len As StringDim myoldpassword As StringDim myoldkeyword As StringDim mynewkeyword As StringDim keyword_count As IntegerPublic doordog1,doordog2 As String Public dog_flag As IntegerPrivate Sub cancel_cmd_Click()c ode_combo.Text=‛‛oldkeyword_txt. Text=‛‛oldkeyword_txt.BackColor=&HC0C0C0 oldkeyword_txt.Enabled=False newkeyword_txt. Text=‛‛newkeyword_txt.BackColor=&HC0C0C0 newkeyword_txt. Enabled=False keyword_okcmd. Enabled=Falsecode_combo.SetFocusEnd SubPrivate Sub code_combo_Click() myCodeTemp=code_combo.Text oldkeyword_txt.BackColor=&HFFFFFF oldkeyword_txt.Enabled=Ture。

VISUAL BASIC 部分代码

VISUAL BASIC 部分代码
Private Sub List1_Click() Text1.FontSize = List1.Text End Sub
Private Sub List2_Click() Text1.FontName = List2.Text End Sub
11 Private Sub label1_Click() For i = 1 To 5 Step 1 s=s+i Next i Print Print "和:"; s, "平均:"; s / 5 End Sub
Private Sub Command2_Click() If Image1.Visible = True Then
Image1.Visible = False Image2.Visible = True ElseIf Image2.Visible = True Then
Image2.Visible = False
List1.AddItem 25 List1.AddItem 30 List1.AddItem 35 List1.AddItem 40 List1.AddItem 45 List1.AddItem 50 List1.AddItem 55 List1.AddItem 60 List2.List(0) = "宋体" List2.List(1) = "黑体" List2.List(2) = "隶书" Combo1.AddItem "黑色" Combo1.AddItem "红色" Combo1.AddItem "蓝色" Combo1.AddItem "黄色" Combo1.Text = "黑色" End Sub
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

课前体验Private Sub Form_Click()For i=1To10For j=1To iPrint"*";Next jPrintNext iEnd Sub【例3-1】Private Sub Form_Click()c1$=Chr$(13)+Chr$(10)msg1$="请输入您的名字:"msg2$="输入后按回车键"msg3$="或单击“确定”按钮"msg$=msg1$+c1$+msg2$+c1$+msg3$name$=InputBox(msg$,"InputBox函数示例","张三")Print name$End Sub【例3-2】Private Sub Form_Click()Msg1$=”Are you Continue to?”msg2$=”Operation Dialog Box”r=MsgBox(msg1$,34,msg2$)Print rEnd Sub【例3-3】编写程序,用MsgBox函数判断是否继续执行。

Private Sub Form_Click()msg$="请确认此数据是否正确"Title$="数据检查对话框"x=MsgBox(msg$,19,Title$)If x=6ThenPrint x*xElseIf x=7ThenPrint"请重新输入"End IfEnd Sub【例3-5】Private Sub Form_Click()Print:PrintFontName="隶书"FontSize=16Print"姓名";Tab(8);"年龄";Tab(16);"职务";Print Tab(24);"单位";Tab(32);"籍贯"PrintPrint"吴大明";Tab(8);25;Tab(16);"职员";Tab(24);"人事科"; Tab(32);"北京"End Sub【例3-6】Private Sub Form_Click()X=InputBox("请输入成绩","学生成绩录入","00")Print xEnd Sub【例3-7】Private Sub Form_Click()Dim x As Single,y As Singlex=InputBox(“请输入x的值”)If x>0Then y=1ElseIf x=0Then y=0Else y=-1Print“x=”;x,”y=”;yEnd Sub【例3-8】Private Sub Form_Click()Dim msg,UserInputmsg="请输入一个字母或0~9之间的数字."UserInput=InputBox(msg)‘输入一个字母或数字If Not IsNumeric(UserInput)Then‘判断是否是数字If Len(UserInput)=1Then‘不是数字时,判断输入的字符串长度是否为1Select Case Asc(UserInput)‘判断输入字母的ASCII 码值Case60To90'在60-90之间为大写字母msg="你输入的是一个大写字母'"msg=msg&Chr(Asc(UserInput))&"'。

"Case97To122'小写字母msg="你输入的是一个小写字母'"msg=msg&Chr(Asc(UserInput))&"'。

"Case Elsemsg="你没有输入字母或数字."End SelectEnd IfElseSelect Case Val(UserInput)'将输入的数值型字符转换为数值Case1,3,5,7,9'如果是奇数msg=UserInput&"是一个奇数。

"Case0,2,4,6,8'如果是偶数msg=UserInput&"是一个偶数。

"Case Else'出界msg="你输入的数字不在0~9范围内"End SelectEnd IfMsgBox msgEnd Sub【例3-8】Private Sub Form_Click()Dim msg,UserInputmsg="请输入一个字母或0~9之间的数字."UserInput=InputBox(msg)‘输入一个字母或数字If Not IsNumeric(UserInput)Then‘判断是否是数字If Len(UserInput)=1Then‘不是数字时,判断输入的字符串长度是否为1Select Case Asc(UserInput)‘判断输入字母的ASCII 码值Case60To90'在60-90之间为大写字母msg="你输入的是一个大写字母'"msg=msg&Chr(Asc(UserInput))&"'。

"Case97To122'小写字母msg="你输入的是一个小写字母'"msg=msg&Chr(Asc(UserInput))&"'。

"Case Elsemsg="你没有输入字母或数字."End SelectEnd IfElseSelect Case Val(UserInput)'将输入的数值型字符转换为数值Case1,3,5,7,9'如果是奇数msg=UserInput&"是一个奇数。

"Case0,2,4,6,8'如果是偶数msg=UserInput&"是一个偶数。

"Case Else'出界msg="你输入的数字不在0~9范围内"End SelectEnd IfMsgBox msgEnd Sub【例3-10】Sub Form_Click()Dim N As Integern=InputBox("Enter N:")‘输入N的值k=1For i=1To N‘循环N次,计算出N!k=k*INext iPrint N;”!=”;k‘数据输出End Sub【例3-12】Dim S,NS=0:N=0Do While S<=100N=N+1S=S+NLoopPrint S,N【例3-13】Private Sub Form_Click()Dim char As StringCount=0char=InputBox("请输入一个字符")While char<>"?"Count=Count+1char=InputBox$("请输入一个字符")WendPrint"输入的字符数是:";CountEnd Sub【例3-14】Private Sub Form_Click()Print"*";For i=1To9Print Tab(i*6);i;Next iPrintFor j=1To9Print j;For k=1To jPrint Tab(k*6);j*k;"";Next kPrintNext jEnd Sub第4章课前体验(1)假定用来输入数学成绩的文本框名称为Text1,该文本框的LostFocus事件过程如下:Private Sub Text1_LostFocus()If Val(Text1.Text)<0Or Val(Text1.Text)>100ThenText1.Text=""Text1.SetFocusEnd IfEnd Sub(2)其他文本框的LostFocus事件类似。

(3)假定按钮名称为Command1,该按钮的Click事件过程如下:Private Sub Command1_Click()If Check1.Value=1Then Sum=Sum+Val(Text1.Text)If Check2.Value=1Then Sum=Sum+Val(Text2.Text)If Check3.Value=1Then Sum=Sum+Val(Text3.Text)If Check4.Value=1Then Sum=Sum+Val(Text4.Text)If Check5.Value=1Then Sum=Sum+Val(Text5.Text)Text6.Text=SumEnd Sub【例4-1】Private Sub Command1_Click()‘在其单击事件中编程For i=1To6‘外循环,控制输出几行For j=1To i‘内循环,控制输出几列Print"*";Next jPrint‘换行Next iEnd Sub【例4-2】Private Sub Text1_Change()Text2.Text=LCase(Text1.Text)Text3.Text=UCase(Text1.Text)End Sub【例4-3】Private Sub Check1_Click()Text1.FontUnderline=Not Text1.FontUnderlineEnd SubPrivate Sub Check2_Click()Text1.FontItalic=Not Text1.FontItalicEnd SubPrivate Sub Option1_Click()Text1.Font="黑体"End SubPrivate Sub Option2_Click()Text1.Font="宋体"End Sub【例4-4】Private Sub Command1_Click()If Option1ThenText1.FontName="宋体"ElseText1.FontName="黑体"End IfIf Option3ThenText1.FontSize=8ElseText1.FontSize=10End IfEnd SubPrivate Sub Command2_Click()EndEnd Sub【例4-5】Private Sub Form_Load()‘在窗体的Load事件中输入列表框的各个项目lstBooks.AddItem"计算机应用基础"lstBooks.AddItem"操作系统"lstBooks.AddItem"数据结构"lstBooks.AddItem"网络技术基础"End SubPrivate Sub cmdAdd_Click()‘单击添加命令按钮时将文本框中输入的内容添加到列表框中lstBooks.AddItem txtItemtxtItem=""End SubPrivate Sub cmdDelete_Click()‘删除列表框中选中的项目lstBooks.RemoveItem lstBooks.ListIndexEnd SubPrivate Sub cmdModify_Click()‘所选项目显示在文本框中,等待修改txtItem.Text=lstBooks.TextcmdAdd.Enabled=FalsecmdDelete.Enabled=FalsecmdModify.Enabled=FalsecmdModify_OK.Enabled=TrueEnd SubPrivate Sub cmdModify_OK_Click()‘所选项目显示在文本框中修改完成后,按下修改确定按钮,更新列表框内容lstBooks.List(lstBooks.ListIndex)=txtItemcmdModify_OK.Enabled=TruecmdAdd.Enabled=TruecmdDelete.Enabled=TruecmdModify.Enabled=TruetxtItem=""End Sub【例4-6】Private Sub Form_Click()Picture3.Picture=Picture1.PicturePicture1.Picture=Picture2.PicturePicture2.Picture=Picture3.PicturePciture3.Picture=LoadPicture()‘把第3个图片框设置为空End sub【例4-7】Private Sub HScroll1_Change()Text1.Text=HScroll1.ValueEnd Sub【例4-8】Private Timer1_Timer()Labe1.Caption=Time$End Sub实训Private Sub Command1_Click()Debug.Print"姓名:";Text1.TextDebug.Print"出生年月:";Text2.TextDebug.Print"籍贯:";Text3.TextIf Option1.Value Then Debug.Print"性别:";"男"If Option2.Value Then Debug.Print"性别:";"女"Debug.Print"民族:";Combo1.TextIf Check1.Value=1Then Debug.Print"健康"Else Debug.Print"不健康"Debug.Print"职称:";Combo3.TextDebug.Print"工资:";Text4.TextDebug.Print"外语熟练程度";HScroll1.ValueDebug.Print"简历:";Text5.TextEnd Sub第5章课前体验Private Sub Command6_Click()Const n=10‘定义常量n的值为10Max=0:K=0‘最高分及所在位置赋初值For i=1To nb(i)=InputBox("请输入第"&i&"个同学的成绩",求最高分)‘输入成绩If b(i)>Max ThenMax=b(i)K=I‘将第i个成绩与最高分Max相比,如果比最高分高,则保存起来End IfNext iPrint"最高分是第"&K&"个同学,其成绩是:"&MaxEnd Sub【例5-1】Option Base1Private Sub Command1_Click()Dim a(3)As Integera(1)=1:a(2)=3:a(3)=5Print a(1)Print a(2)Print a(3)End Sub【例5-2】For i=1To10b(i)=InputBox("请输入第"&i&"个数")Next i【例5-3】For i=1To2For j=1To2b(i,j)=i+jNext jNext i【例5-4】Dim S(3,2)As Integer程序如下:For i=0To3Print Tab(5);‘输出位置定位For j=0To2S(i,j)=i*2+j‘给各元素赋值Print S(i,j);图5-4使用二维数组打印出的图形Next jPrint‘换行Next i【例5-5】Private Sub Form_Click()Dim s(5)As Integer'定义数组SConst n=5For i=1To ns(i)=Val(InputBox("请输入第"&LTrim$(Str$(i))&"个数",数据排序))‘输入n个数,转换成数值后保存在数组中。

相关文档
最新文档