Option Explicit ' 强制变量声明Sub DemoSub() MsgBox "执行完成"End SubFunction AddNum(a As Double, b As Double) As Double AddNum = a + bEnd Function
变量声明
vb
UTF-8|7 Lines|
Dim filePath As StringDim lastRow As LongDim amount As DoubleDim isDone As BooleanDim dataArr As VariantDim ws As WorksheetConst SHEET_NAME As String = "数据"
If Range("A1").Value = "" Then Exit SubEnd IfIf val = "YL7" Then res = "高价值品"ElseIf val = "YL026" Then res = "包装类"Else res = "未定义"End IfSelect Case code Case "YL7" res = "高价值品" Case "YL026" res = "包装类" Case Else res = "未定义"End Select
循环
vb
UTF-8|16 Lines|
For i = 2 To lastRow Cells(i, 2).Value = "已处理"Next iFor i = lastRow To 2 Step -1 If Cells(i, 1).Value = "" Then Rows(i).DeleteNext iFor Each cell In Range("A2:A5") cell.Value = Trim(cell.Value)Next cellDo While n <= 3 Debug.Print n n = n + 1Loop
退出
vb
UTF-8|4 Lines|
Exit ForExit DoExit SubExit Function
字典
vb
UTF-8|21 Lines|
Dim dict As ObjectSet dict = CreateObject("Scripting.Dictionary")dict.CompareMode = vbTextComparedict.Add "key", "value" ' 添加dict("key2") = "value2" ' 添加/覆盖dict.Exists("key") ' 判断是否存在dict("key") ' 取值dict.Count ' 数量dict.Remove "key" ' 移除dict.RemoveAll ' 清空' 常见用途:去重与累计For i = 2 To UBound(dataArr, 1) keyName = dataArr(i, 2) & "-" & dataArr(i, 9) If dict.Exists(keyName) Then dict(keyName) = dict(keyName) + CDbl(dataArr(i, 14)) Else dict.Add keyName, CDbl(dataArr(i, 14)) End IfNext i