Excel / VBA Sep 2012 Dick Lam
Excel / VBA
Sep 2012
Dick Lam
提纲I. Excel / VBA 结构II. 变量 / Variable
III. 物件 / Object
IV. 程式邏輯 / Loop
V. 簡單應用VI. 資料庫VII. 通用程式應用VIII. 在 Excel/VBA 讀取資料庫
首先
Excel / VBA 结构• Alt + F11 打開設計模式• 主要作用 :
– 自定義函数 (function), 作單元格计算 ; 如sum()
– 指令 (command), 一連串動作或判断以決定何種效果或计算結果
• 亦可透過外部連結 , 抽出資料庫數據• 更可儲存資料至資料庫
• 最重要是 logic, 活用 if …. Then … Else 格式思維
• Function XYZ( ) as Type– Private vs. Public
• Sub XYZ– Private vs. Public
Excel / VBA 结构
Function
Sub
变量 / Variable宣示 : Dim
•String / Long / Double
•Constant
•範圍 : Public / Module / Procedure
•Option Explicit
Object 物件• Application / Activewindow
• Workbook / Worksheet / Range– No object like Cell– Cell = Range, e.g. range(“a1”)
• Controls: ComboBox / List / Button / Checkbox
Characteristics of Object• Event / 事件
– Worksheet• Doubleclick• SelectionChange• Activate
• Property / 屬性– Worksheet: Name– Range: font.color / interior.color
• Method / 方法– Worksheet: calculate / activate
Debug/ 除錯• [F8] to step forward each command in the
code, or;
Debug/ 除錯• Set a breakpoint to a place you want to
start debugging
程式邏輯 / Loop• If .. Then
• If .. then .. else
• IF…Then…else if
• If…Then…Else IF 语句中的 Else IF 条件判断式的数量没有限制,但是在有多个 Else IF 判断式的情况下,可能阅读起来很吃力。
• 当判断的对象是单一条件时,使用 Select Case 语句更容易解决前面的困扰。
• Select case .. case .. case else
• For…Next
• For Each…Next
• For…Next 语句即用于指定次数秋重复执行一组语句。• For Each…Next 语句针对一个数组或集合中的每个元素重复执行一组语句。
• Do Until…Loop
• Do While…Loop
• Do Until…Loop 语句是当条件为 False 时,重复执行语句,当条件为 True 时结束循环;• Do While…Loop 语句则是当条件为 True 时,重复执行语句,条件为 False 时结束循环。
簡單應用• fMax / fMin
• NoShortQty
• FileListName
• fRegion
• GetComment
• DoubleClick
ActiveX Data Object
資料庫• Database
– Connection String• SQL:
"Provider=sqloledb;Server=192.168.0.10;UID=sa;PWD=ydyester;Initial Catalog=yestertest“
• Microsoft Access:
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\Works\2012 Training\ExcelVBA\ERP.accdb;Persist Security Info = False"
資料庫– Connection
• Dim DB as new adodb.connection• DB.open gConnectionString
• Table: Recordset• Dim xRecord as new adodb.recordset• xRecord.open “select * from bom”,db,adopenstatic
資料庫• Query
通用程式應用• Dbdownload(xTable, xFieldRange, xRow,
xCriteria, xOrder)
Workshop forProduction Materials Plan
Tips & Tricks• Design the model
• Work out the middle layer of the model, i.e. various working worksheet
• Conclude with a summary/report
• Find the range address
• Find the value of a particular cell
• Write formula in a particular cell in VBA
• Define the interval of the model
• 有一百樣物料缺 , 究竟有沒有只追一種物料便即時可以開工單 ?
• 如果追一種物料 , 是否有資料告知同時要追另外哪些料才可開工單 ?
• 突然有一系列急單 , 究竟欠哪些料 ?
• 某一種物料是哪成品需要 , 多少及欠多少 ?
更多的要求