Hom's Blog


VB基础篇-1

最近Excel处理数据用得多. 还是复习一下VB吧. 手头没有书,就随便搞点基础看看就好了. VB是VBA, VBscript, VB.net的基础, 好好复习还是有点好处的. 不过语法和别的语言有点差异大了点..据说VBS还可以插入html像JS一样使用..但现代浏览器可能淘汰这个危险的玩意了吧..微软的大计木有实现啊~

  • 第一篇只谈基础, 包括最基础的变量,数组,判断,循环.
  • 第二篇谈函数,子过程,结构,对象.
  • 第三篇谈特殊内容.
  • 第四篇总结各种语句,自语句,过程.
  • VBA篇专谈VBA特殊东东.

变量

Byte 、SByte、UShort、Short、UInteger、Integer、ULong、Long、Decimal、Single 或 Double。

对象变量 通用型定义:
Dim var As Object
对象变量赋值和常规变量不同,需要使用Set语句.
Set var = Worksheets(“Sheet1”)

数组

判断

=, <>,

If..then..elseif..else..End If 语句 ref

  • If一般差异都不大..没啥好注意的..
  • If可以一行化,使用:可以分隔statements.
' 关键词: If, Then, Elseif, Else, End If
' 格式规范:
' Multiple-line syntax:
If condition [ Then ]
    [ statements ]
[ ElseIf elseifcondition [ Then ]
    [ elseifstatements ] ]
[ Else
    [ elsestatements ] ]
End If
' Single-line syntax:
If condition Then [ statements ] [ Else [ elsestatements ] ]

' 示例
Private Function CheckIfTime() As Boolean
    ' Determine the current day of week and hour of day.
    Dim dayW As DayOfWeek = DateTime.Now.DayOfWeek
    Dim hour As Integer = DateTime.Now.Hour
    ' Return True if Wednesday from 2 to 4 P.M., or if Thursday from noon to 1 P.M.
    If dayW = DayOfWeek.Wednesday Then
        If hour = 14 Or hour = 15 Then
            Return True
        Else
            Return False
        End If
    ElseIf dayW = DayOfWeek.Thursday Then
        If hour = 12 Then
            Return True
        Else
            Return False
        End If
    Else
        Return False
    End If
End Function
' If A > 10, execute the three colon-separated statements in the order that they appear
If A > 10 Then A = A + 1 : B = B + A : C = C + B

Select Case ref

  • 和某些语言不同,VB的select语句只会选择首个匹配后,不执行后续的,所以不用break什么的跳出.本来其语言就支持多个范围.
  • testexpression一般是变量名, 也可以是一个表达式.
  • expressionlist匹配值表达式列表(多个表达式可以用逗号隔开),表达式可以是 表达式1 To 表达式2,可以是Is 比较运算符表达式(>0),也可以是一般的值表达式(Is = value的特殊情况).
  • Exit Select 可以在statements中跳出select不执行statements的后续,一般搭配If等使用. 不常用.
  • Case部分可以使用一行化写法: Case 1, 3, 5: MsgBox "Hello" (冒号分隔)
' 关键词: Select, Case, Case Else, End Select
' 格式规范:
Select [ Case ] testexpression
    [ Case expressionlist
        [ statements ] ]
    [ Case Else
        [ elsestatements ] ]
End Select
' 示例
Dim number As Integer = 8
Select Case number
    Case Is <= 5
        Debug.WriteLine("Not more than 5, inclusive")
    Case 6, 7, 8
        Debug.WriteLine("Between 6 and 8, inclusive")
    Case 9 To 10
        Debug.WriteLine("Equal to 9 or 10")
    Case Else
        Debug.WriteLine("More than 10, inclusive")
End Select

循环

For Next 循环 ref

  • 有限式数值循环. For 变量 = 开始 To 结束 Step 步长 .... Next .
  • 循环是包括end的.即C的for (datatype i=start;i<=end;i+=step){..} (step>0时..)
  • 和一般语言一个显著差异是人家用break他用exit For. continue For和一般差不多.
  • Next后面的变量名可省略,不过建议写上比较明晰, 尤其在嵌套循环时.
  • start, end, step三个值在循环开始时就确定下来,即使用变量来改变也无效. 但循环变量可以中途改变.
  • 可以尝试用Try …Catch…Finally 语句捕捉异常,在 Finally 块的末尾使用 Exit For。
' 关键词: For, To, Step, Next, Continue For, Exit For
' 格式规范:
For counter [ As datatype ] = start To end [ Step step ]
    [ statements ]
    [ Continue For ]
    [ statements ]
    [ Exit For ]
    [ statements ]
Next [ counter ]
' 示例
For index As Integer = 1 To 100000 Step 2
    If index >= 5 And index <= 8 Then
        Continue For
    End If
    Debug.Write(index.ToString & " ")
    If index = 10 Then
        Exit For
    End If
Next

For Each Next 循环 ref

  • 有限式指定集合循环.
  • 和For Next不同, 使用 Each 变量 In 集合 来代替 变量=开始 To 结束 Step 步长
  • 集合可以是数组, 也可以是迭代器.
  • 避免在循环体内更改 element 的值,虽然允许。更改group的值不会影响集合或其组件,因为循环前就事先确定了循环集合。
' 关键词: For Each, In, Next, Continue For, Exit For
' 格式规范:
For Each element [ As datatype ] In group
    [ statements ]
    [ Continue For ]
    [ statements ]
    [ Exit For ]
    [ statements ]
Next [ element ]
' 示例
Dim numbers() As Integer = {1, 4, 7}
Dim letters() As String = {"a", "b", "c"}
For Each number As Integer In numbers
    For Each letter As String In letters
        Debug.Write(number.ToString & letter & " ")
    Next
Next
Debug.WriteLine("")

' VBA示例
Dim wks As Worksheet
For Each wks In Worksheets
    MsgBox "工作表的名字是:" & wks.Name
Next wks

Dim cell As Range, rng As Range
Dim i As Long 
Set rng = Range("B2:B9")
i = 0
For Each cell In rng
    If cell.Value > 80 Then
        i = i + 1
    End If
Next cell
MsgBox "共有" & i & "名学生超过80分."

' 迭代器示例
Public Sub ListEvenNumbers()
    For Each number As Integer In EvenSequence(5, 18)
        Debug.Write(number & " ")
    Next
    Debug.WriteLine("")
    ' Output: 6 8 10 12 14 16 18
End Sub
Private Iterator Function EvenSequence(
ByVal firstNumber As Integer, ByVal lastNumber As Integer) _
As System.Collections.Generic.IEnumerable(Of Integer)
    ' Yield even numbers in the range.
    For number = firstNumber To lastNumber
        If number Mod 2 = 0 Then
            Yield number
        End If
    Next
End Function

Do Loop 循环 ref

  • 条件式不定次数循环. Do While 条件 ...Loop, Do Until 条件 ...Loop, Do ...Loop While 条件, Do ...Loop Until 条件 四种组合,后两者必须至少干一次.
  • while是真时才进行循环, until是假时才进行循环.
' 关键词: Do, Loop, While, Until, Continue Do, Exit Do
' 格式规范:
Do { While | Until } condition
    [ statements ]
    [ Continue Do ]
    [ statements ]
    [ Exit Do ]
    [ statements ]
Loop
-or-
Do
    [ statements ]
    [ Continue Do ]
    [ statements ]
    [ Exit Do ]
    [ statements ]
Loop { While | Until } condition
' 示例
Dim index As Integer = 0
Do While index <= 10
    index += 1
    If index >= 5 And index <= 8 Then
        Continue Do
    End If
    Debug.Write(index.ToString & " ")
    If index = 10 Then
        Exit Do
    End If
Loop
index = 0
Do
    Debug.Write(index.ToString & " ")
    index += 1
Loop Until index > 10

While End While 循环 ref

  • 不建议使用, 建议使用do while loop循环. 官方说出了重复一组语句无限次时推荐使用…无限次…
' 关键词: Do, Loop, While, Until, Continue While, Exit While
' 格式规范:
While condition
    [ statements ]
    [ Continue While ]
    [ statements ]
    [ Exit While ]
    [ statements ]
End While
' 示例
Dim index As Integer = 0
While index < 100000
    index += 1
    If index >= 5 And index <= 8 Then
        Continue While
    End If
    Debug.Write(index.ToString & " ")
    If index = 10 Then
        Exit While
    End If
End While

Goto语句 ref

  • 不建议使用的语法.但有时有特殊功效.
  • 只能跳转它所在的过程内的行,必须有行标签.
  • 在和其余循环一起时不能从外部分支到内部标签.
  • Try…Catch…Finally 构造中, 跳转有相应规则,参考上面的ref.
' 关键词: Goto
' 格式规范:
line1:
	statement
GoTo line1
line2:
	statement

' 示例
	Sub gotoStatementDemo()
        Dim number As Integer = 1
        Dim sampleString As String
        ' Evaluate number and branch to appropriate label.
        If number = 1 Then GoTo Line1 Else GoTo Line2
Line1:
        sampleString = "Number equals 1"
        GoTo LastLine
Line2:
        ' The following statement never gets executed because number = 1.
        sampleString = "Number equals 2"
LastLine:
        ' Write "Number equals 1" in the Debug window.
        Debug.WriteLine(sampleString)
    End Sub

With End With 语句 ref

  • 针对对象进行一系列的操作.简化不断输入对象名的烦恼.
  • 在With语句块内,对象的属性和方法直接使用.属性名=.. 或.方法()来调用
  • 嵌套语句中,可以对子对象进行进一步操作(见示例).
  • 同样可以应用于结构, 但是只能读取结构的成员或调用的方法的值,如果尝试为结构的成员赋值,则将收到错误。
' 关键词: With, End With
' 格式规范:
With objectExpression
    [ statements ]
End With
' 示例
Dim theWindow As New EntryWindow
With theWindow
    With .InfoLabel
        .Content = "This is a message."
        .Foreground = Brushes.DarkSeaGreen
        .Background = Brushes.LightYellow
    End With
    .Title = "The Form Title"
    .Show()
End With

Reference

  1. 微软VB参考
  2. 微软VB语言参考


◆ 本文地址: http://platinhom.github.io/2015/09/28/VB_Basic_1/, 转载请注明 ◆

前一篇: Excel多表格进行同时排序
后一篇: 多表格数据统一进行多类回归拟合参数


Contact: Hom / 已阅读()
Source 类别: Coding  标签: VB