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

用法:

 

posted @ 2020-10-21 11:13  cctext  阅读(1326)  评论(0编辑  收藏  举报