excel宏的用法

在不少時間excel中並沒有一些我們想要的函數,這時候我們可以在*.xls[x]的中定義宏,定義了宏後需要注意兩項問題:

  • 1)文件需要保存爲*.xlsm(否則保存爲*.xls[x]會丟失宏函數);

  • 2)再次打開*.xlsm時,會提示是否啓動宏,必須啓用才能使用宏,否則將會禁用宏。

在*.xls[x]中定義宏函數:

我這裏希望對一個字符串拆分,比如:希望將A列中‘[1, 2, 3, 10, 11]’的數據拆分爲C,D,E,F,G 5列。

此時在excel的菜單-》工具-》宏-》Visual Basic 編輯器

 之後會打開宏編輯器,在菜單-》插入-》模塊,插入“模塊1”,“模塊2”

在模塊1中寫入拆分函數:

Function splitFunc(Rng As Range, splitChar As String, idx As Integer) As String
    Dim replaceChar As String
    '替換[、]
    replaceChar = Replace(Rng.Text, "[", "")
    replaceChar = Replace(replaceChar, "]", "")
    
    '按照指定字符串進行分割,然後返回指定分割後數組項
    splitFunc = Split(replaceChar, splitChar)(idx)
End Function

用法:

在模塊2中寫入是否連續判斷函數:

Function isLinkNum(Rng1 As Range, Rng2 As Range, Rng3 As Range, Rng4 As Range, Rng5 As Range) As Integer
    Dim c1 As Integer
    Dim c2 As Integer
    Dim c3 As Integer
    Dim c4 As Integer
    Dim c5 As Integer
    
    c1 = CInt(Rng1.Text)
    c2 = CInt(Rng2.Text)
    c3 = CInt(Rng3.Text)
    c4 = CInt(Rng4.Text)
    c5 = CInt(Rng5.Text)
    
    If ((c5 - c4 = 1) And (c4 - c3 = 1) And (c3 - c2 = 1) And (c2 - c1 = 1)) Then
        isLinkNum = 1
    Else
        isLinkNum = 0
    End If
End Function

用法:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章