使用描述性變數命名

程式碼中的描述性名稱和結構有助於使註釋變得不必要

Dim ductWidth  As Double
Dim ductHeight As Double
Dim ductArea   As Double

ductArea = ductWidth * ductHeight

比…更好

Dim a, w, h

a = w * h

當你將資料從一個位置複製到另一個位置時,無論是單元格,範圍,工作表還是工作簿,這都非常有用。通過使用以下名稱來幫助自己:

Dim myWB As Workbook
Dim srcWS As Worksheet
Dim destWS As Worksheet
Dim srcData As Range
Dim destData As Range

Set myWB = ActiveWorkbook
Set srcWS = myWB.Sheets("Sheet1")
Set destWS = myWB.Sheets("Sheet2")
Set srcData = srcWS.Range("A1:A10")
Set destData = destWS.Range("B11:B20")
destData = srcData

如果在一行中宣告多個變數,請確保為每個變數指定一個型別,如:

Dim ductWidth As Double, ductHeight As Double, ductArea As Double

以下只會宣告最後一個變數,而第一個變數將保留為 Variant

Dim ductWidth, ductHeight, ductArea As Double