二、VBS基础知识

本文深入介绍了VBS的基础知识,包括变量的声明与使用,如Option Explicit的重要性,常数的声明与赋值规则,以及固定长度和动态数组的定义。还涵盖了运算符和控制结构,如If...Then...Else、For...Next等,并提到了函数和过程的运用,以及一些常用的VBS函数类别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        该章我们将讲解vbs的基础知识,主要内容如下:

一、变量

    Option Explicit 
    Dim num_a
    num_a = "Hello " & vbNewLine & "world!" 
    MsgBox "Hello World!", 65, "MsgBox Example" 
    MsgBox num_a & vbCr & "num_a 类型为:" & TypeName(num_a) & vbLf &_
           "num_a 类型的符号数:" & VarType(num_a)


           备注
            1、Option Explicit :表示之后的变量必须显示声明,否则程序将报错
            2、变量的定义与声明必须分开说明
            3、vbcr:回车符; vblf:换行符 ; vbcrlf:回车与换行符 ; vbNewLine:新行字符
            4、_:表示分行的数据为同一行数据 <单行拆分>

            5、:表示通过“:”可将多行的数据写在一行上<多行合并>
 
二、常数

   Const Con_NUM_1="China"
   MsgBox "常数值为:" & Con_NUM_1

        

        备注
        1、常数在声明和赋值必须一步完成
        2、常数在程序运行期间,不能被重新赋值,否则,报错
 
三、数组
    1、固定长度数组

      Dim arr_a(2)
      arr_a(0)=0
      arr_a(1)="a"
      arr_a(2)="2"
      MsgBox "数组 arr_a的最大下标为:" & UBound(arr_a)
      MsgBox "数组 arr_a的数组元素分别为:"


      For i=0 To UBound(arr_a)
            MsgBox "第" & i & "个元素为:" & arr_a(i)
      Next


 
   
2、动态数组

     Dim arr_b()
     Dim j
 
     ReDim arr_b(0)
     arr_b(0)=0
 
     ReDim Preserve arr_b(1)
     arr_b(1)=1
 
     For j=0 To UBound(arr_b)
          MsgBox "第" & j & "个元素为:" & arr_b(j)
     Next


        备注
        1、要定义动态数组,首次定义时,数组长度不指定
        2、Preserve:表示重新调整数组长度时,保留数组之前的内容,同时数组长度的调整次数无限制
   
四、运算符

     MsgBox "幂 2^4="   & 2^4
     MsgBox "除 5.1/4="   & 5.1/4 
     MsgBox "整除 2\4=" & 2\4 
     MsgBox "求余 (5)mod(3)=" & (5)mod(3) 
     MsgBox "不等于 3<>2: " & (3<>2)
     MsgBox "逻辑与 0 and 2: " & (0 and 2) 
     MsgBox "逻辑或 0 or 2: " & (0 or 2) 
     MsgBox "逻辑非 not 2: " & (Not 2) 
     MsgBox "逻辑异或 1 xor 1: " & (1 Xor 1) 
     MsgBox "逻辑等价 1 eqv 2: " & (1 eqv 2) 
     MsgBox "逻辑隐含 1 imp 2: " & (1 imp 2) 


 
五、控制结构
        1、 if..then..else
   

         Dim num_c,num_d,MyVar
         num_c = 3
         num_d = 2
   
         If num_c > num_d Then
              yVar = MsgBox("pass",65,"result")
         Else
              MyVar = MsgBox("fail",65,"result")
         End If



 2、 select..case

Dim num_e
num_e = 7
Select  Case num_e
   Case 1
      MsgBox "1"
   Case 3
      MsgBox "3"
  Case Else
      MsgBox "default"
End Select


 
 3、 do..loop

Dim num_f
num_f = 10
Do While num_f > 8
    num_f = num_f -1
    MsgBox num_f
Loop
Do 
  num_f = num_f -1
  MsgBox num_f
Loop While num_f > 3



 
 4、 while..wend

 Dim num_g
 num_g = 4
 While num_g > 1
     MsgBox num_g
     num_g = num_g - 1
 Wend




 
5、 for..next

Dim num_h
For num_h=0 To 3
  MsgBox num_h
Next


   
 6、 退出循环或过程的方法

 'Exit Do
 'Exit For
 'Exit Function
 'Exit Property
 'Exit Sub


六、过程和函数
    1、函数

    Function fun(a,b)
        fun = a+b
    End Function
    MsgBox fun(1,3)


    2、过程  

     Sub su(a,b)
              MsgBox a+b
     End Sub
     su 1,2


    
 
   3、备注
           function,sub均可带参数,同时function可有返回值,sub不能带返回值
   
七、常用函数
    1、转换函数

'asc:返回与字符串的第一个字母对应的 ANSI 字符代码
 MsgBox Asc("ABC") '65
 
 'chr:返回与指定的 ANSI 字符代码相对应的字符
 MsgBox Chr(65)  'A
 
 'strComp:返回字符串比较的结果,-1:小于 0:等于 1:大于
 MsgBox StrComp("a","b")
 
 'StrReverse:返回字符串,此字符串与指定字符串顺序相反
 MsgBox StrReverse("ABCDE")
 
 'cstr:将指定表达式转换为字符串
 MsgBox TypeName(CStr(111))

 'cint:将指定的表达式转换为数字
 MsgBox TypeName(CInt("123"))


 
   
2、判断函数

'isarray:返回指定变量是否为数组
 Dim arr_1(3)
 MsgBox IsArray(arr_1)
 
 'isdate:返回指定变量是否为日期内容
 MsgBox IsDate("2011-7-7")
 
 'isempty:返回 Boolean 值,指明变量是否已初始化,未初始化返回True,初始化返回False
 Dim bool
 MsgBox IsEmpty(bool) 'True 未初始化
 bool=1
 MsgBox IsEmpty(bool) 'false 已初始化
 
 bool=Null
 MsgBox IsEmpty(bool) 'false 已初始化
 
 bool=Empty
 MsgBox IsEmpty(bool) 'true 未初始化
 
 'IsNumeric:返回boolean值,指明变量是否为数字
 MsgBox IsNumeric(3)
 
 'isnull:指明表达式是否不包含任何有效数据,含有返回True,未含有返回False
 Dim isn
 MsgBox IsNull(isn)
 
 'isobject:返回指定变量是否是对象,是对象返回True,不是对象返回False
 Dim obj
 Set obj = CreateObject("Wscript.shell")
 MsgBox IsObject(obj) 


 
   
3、时间函数

'根据计算机系统设定的日期和时间返回当前的日期和时间值
 MsgBox Now()
 
 '返回当前年月日,还有year(),month(),day()
 MsgBox Date()
 
 '返回当前时分秒,还有hour(),minute(),second()
 MsgBox Time()
 
 '返回星期数,日-六 分别为1-7
 Dim mydate
 mydate = #2011-7-7#
 MsgBox Weekday(mydate) '返回5,代表星期四
 
 '返回系统日期与指定日期相减后的日期
 MsgBox DateAdd("yyyy",1,Date())  '返回系统日期一年后的日期
  '备注:yyyy--代表年  q--代表季度  m d--代表月 日
  'y--代表一年的日数  w--代表一周的日数  h n s --代表时分秒
 '返回两个日期的间隔日期
 MsgBox DateDiff("m","2011-7-1","2012-9-3") '返回14,代表相差14个月


 
    4、其他函数

'将指定字符串转换为大小写
 MsgBox UCase("AaA")
 MsgBox LCase("AaA") 
 
 '返回字符串的长度
 MsgBox "china长度为:" & Len("china")
 
 '截取字符串
 MsgBox "china 前3个字符为:" & Left("china",3)
 MsgBox "china 后3个字符为:" & Right("china",3)
 MsgBox "china 从第2个字符开始,后3个字符为:" & mid("china",2,3)
 
 '返回某字符串在另一字符串中第一次出现的位置
 MsgBox "n在china的第" & InStr(2,"china","n",1) & "个位置" 
 '备注: 2--表示从第2个字符开始搜索,1--表示文本比较
 


 
八、类

'定义类
    Class Stu
          '定义带参数的函数,并有返回值
            Function output_fun(fir,sec)
              output_fun = fir & sec
          End Function
     
         '定义带参数的过程
           Sub output_sub(fir)
             Const con = "Mary,"
             MsgBox con & fir
         End Sub
   End Class

   '实例化变量
    Set s = New Stu
    
   '调用类中的函数,并给出实参
    MsgBox s.output_fun("Hello"," world") => Hello world
    MsgBox s.output_fun(1,2)              => 12
    
   '调用类中的过程,并给出实参
    s.output_sub("How are you?")          => Mary,How are you?



 九、综合应用

'例1:将数组中的元素由小到大进行排序
 Function sort() 
   Dim arr_sort,i,j
   arr_sort = Array(1,3,5,7,9,2,4,6,8,10,-1,100)
  
   For i=0 To UBound(arr_sort)-1
       For j=0 To UBound(arr_sort)-1-i
           temp=0
           If arr_sort(j) > arr_sort(j+1) Then
               temp = arr_sort(j)
               arr_sort(j) = arr_sort(j+1)
               arr_sort(j+1) = temp
           End if
       next
   next
  
  For i=0 To ubound(arr_sort)
      MsgBox arr_sort(i)
  Next
End Function 
sort()
           
'例2:双色球摇奖机
Function DoubleColourBall
	Dim  red_ball(6)          
	Dim  red_ball_temp(6)
	Dim  array_split
	Dim  input_value
	
	input_value = InputBox ("请选择,是否显示摇奖过程: " & vbcr & vbcr & "Y or N (不区分大小写)","用户输入框","N")
	
	Randomize
	'摇红色球,并去除重复号码
	For i=0 To 5
		Randomize 
		Do
			Randomize 
			red_ball_temp(i) = Int(32 * Rnd + 1)

			If i>=1 Then
				array_split = array_split  & " " & red_ball_temp(i-1) & " "
			End If

			if CBool(InStr(1,array_split,CStr(red_ball_temp(i)))) = False then
				red_ball(i) = red_ball_temp(i)
				Exit  Do 
			end if
		Loop
		
		If UCase(input_value) = "Y" Then
			MsgBox "    *红色球*" & vbcr & vbcr & "第" & i+1 & "个中奖号码为:" & red_ball(i),1,"开奖号码"
		End If
	Next
	
	'摇蓝色球
	Randomize
	Dim blue_ball
	blue_ball = Int(12 * Rnd + 1)
	
	If UCase(input_value) = "Y" Then
			MsgBox "  *蓝色球*" & vbCr & vbCr  & "中奖号码为:" & blue_ball ,1,"开奖号码"
	End If
	
	'对号码进行排序
	For i=0 To 4
		For j=0 To 4-i
			Dim temp
			If red_ball(j) > red_ball(j+1) Then
				temp = red_ball(j)
				red_ball(j) = red_ball(j+1)
				red_ball(j+1) = temp
			End if 
		next
	Next
	
	'显示最后结果
	Dim award_number
	award_number = Join(red_ball)
	MsgBox "   本期双色球中奖号码" & vbCr & vbCr & "红色球: " & award_number & vbcr & "蓝色球: " &  blue_ball ,1,"开奖结果"
End Function

Call DoubleColourBall()


显示结果:

 

'例3:将文件中的指定位置的#号以特定字符替换
Function write_txt(txt_path)  
   Const ForReading =1,ForWriting = 2,ForAppand = 8  
   Dim fso,file  
   Set fso = CreateObject("Scripting.fileSystemObject")  
   Set file = fso.OpenTextFile(txt_path,ForWriting,True)  
   
   '写入366个#  
   For i=0 To 365
   		file.Write("#") 
   next
   Set file = Nothing

   Dim input_date,str,input_month,input_day,mouth_day,total_day
   input_date = InputBox("请输入日期,格式为月日,中间以空格隔开")
   
   split_date = Split(input_date," ",-1,1)               
   input_month = CInt(split_date(0))            '输入的月份
   input_day = CInt(split_date(1))              '输入的日数
   
   '判断输入的日期是否正确
   If input_month < 1 Or  input_month >12 Then
   		MsgBox "月份错误,退出!"
   		Exit function
   End If
   
   Select  Case input_month  
  	Case 1,3,5,7,8,10,12
     	max_day=31 
  	Case 4,6,9,11  
     	max_day=30  
  	Case Else  
     	max_day=28
   End Select 
    
   If input_day < 1 or input_day > max_day Then
   		MsgBox "日数错误,退出!"
   		Exit function
   End if
   
   str = InputBox("请输入找到对应的日期后,用以替换#号的符号") 
   mouth_day = Array(31,28,31,30,31,30,31,31,30,31,30,31) '每月的最大天数,不考虑闰年
   
   '计算天数
    total_day = 0
    If input_month>1 then
        For i=0 To input_month-2
    		total_day = total_day + mouth_day(i)
    	Next
    	total_day = total_day + input_day
    Else
    	total_day = input_day
    End If
    
    'MsgBox "输入的天数在第" & total_day & "个位置"


    '将对应位置的#号,用输入的字符将其替换
    If fso.FileExists(txt_path) Then  
    	Set file = fso.OpenTextFile(txt_path,ForReading)  
      	Do While (Not file.AtEndOfLine)  
     	   msg = file.ReadLine  
       	Loop  
  	Else  
    	MsgBox txt_path & " is't exists!"  
  	End If  
  	
    split_after_str = Replace(msg,"#",str,total_day,1)
    Set file = Nothing
    
    '将修改的后字符,重写入文件
    fso.DeleteFile(txt_path)
    fso.CreateTextFile(txt_path)
    Set file = fso.OpenTextFile(txt_path,ForAppand,True)  

    For i=0 To total_day-2
   		file.Write("#") 
    Next
    file.Write(split_after_str)
    
    Set file = nothing 
    Set fso = Nothing  
 
End function   

Call write_txt("c:\aaa.txt")



 



 
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值