2017年11月3日 星期五

EXCEL 記錄點點


位置偏移,指定指標,帶入Range().Offset(y,x)

Private Sub CommandButton1_Click()
    
     Set curs = Selection
     addr = curs.Address()
     '位置偏移
     Range(addr).Offset(1, 0) = cost_box.Text
End Sub


關於 Sub 和 Funcation 

         'sub 
 可以傳呼 VBA\Button\Event , 不能Return
'Function
    能回傳值,但不是必要選項
    能傳呼VBA\Button\Event,但是不能列出LIST的值,必須自己列出
    如果是公共的,在 Excel 將出現在當前工作簿的函數庫 裡面
範例:
Sub WriteValues()
    Dim Amount As Long
    ' Get value from GetAmount function
    Amount = GetAmount
End Sub

Function GetAmount() As Long
    GetAmount = 55
End Function


關於ByVal 跟 ByRef
Sub Test()

    Dim x As Long

    ' 變數,x不會改變
    x = 1
    Debug.Print "x 之前(變數)"; x
    SubByVal x
    Debug.Print "x 之後(變數)"; x

    ' Pass by reference - x will change
    x = 1
    Debug.Print "x 之前(參考)"; x
    SubByRef x
    Debug.Print "x 之後(參考)"; x

End Sub

Sub SubByVal(ByVal x As Long)
    ' x 使用變數,輸出不會改變
    x = 99
End Sub

Sub SubByRef(ByRef x As Long)
    ' x 使用參考,輸出會改變
    x = 99
End Sub

取得目前欄位位置!


set curs = Selection
addr = curs.Address()


回傳值的方式
Function GetAmount() As Long
    ' Returns 55
    GetAmount = 55
End Function

Function GetName() As String
    ' Returns 字串
    GetName = "字串"
End Function

字元轉換方式
        Dim ox = New String(5) {}
        Dim it As Integer
        Dim c As Char

         '把a 轉換成數字
        it = Asc("a")
        If IsNumeric(it) Then
            MsgBox(it & "數字")
        End If

        '把數字轉成 ASCII
        For i = 0 To 5
            c = Chr(97 + i)
            ox(i) = c
        Next

        For Each d In ox
            MsgBox(d)
        Next

空值判斷,就是欄位沒東西
             IF IsEmpty( value ) Then
                   MsgBox (value " & vbNewLine & 空白的")
             END IF
   
             IF IsNumeric(it) Then
                   MsgBox(it & "不是數字")
             End If



參考 : 用Range? 用Cells?