VBA常用技巧2

1. UserForm的初期设定
    最简单的方法:
        UserForm1.Show
    想要初期化Form里的值,可以:
        Sub Macro1()
            Load UserForm1
            With UserForm1
                .TextBox1.Value = ActiveCell.Value
                .TextBox1.SetFocus
                .Show
            End With
        End Sub
    也可以用Initialize事件:
        Private Sub UserForm_Initialize()
            TextBox1.Value = ActiveCell.Value
            TextBox1.SetFocus
        End Sub

2. Range对象的引用
    有时候想要用名称作为参数传递给Range对象,怎么做呢?
    在工作表里用鼠标选择一个范围,然后在左上角的“Name Box”里输入名称,这样就给这个范围里所有的单元格赋予了名称,以后就可以用Range("名称")引用这个范围了。来看个例子:
    Dim No As Variant
    Dim rcd As Range
    No = ComboBox1.Value
    '寻找“编号”范围里是No的Range对象
    Set rcd = Range("编号").Find(What:=No, LookAt:=xlWhole)
    
    If No = "新规" Then
        '插入一空行
        rcd.EntireRow.Insert
        '取得空行前一行的Range对象
        Set rcd = rcd.Offset(-1)
        rcd.Value = rcd.Offset(-1).Value + 1
    End If

3. 日期,时刻函数

文字列

时间间隔

yyyy
q
m
y 年间通算日
d
w 周日
ww
h 小时
n
s

DateDiff(interval, date1, date2, firstdayofweek, firstweekofyear)函数:
计算date1和date2之间的间隔,按照interval指定的单位返回函数。
date1,date2可以是日期值或者字符串;后面两个参数可以省略,如果省略,则前者是星期日,后者是1月1日所在的那一周。
例如,要计算从现在到明年还剩下多少天,多少时间:
    Dim nYear as Long
    Dim nDays as Long
    Dim nHours as Long
    nYear = DateSerial(Year(Now) + 1, 1, 1)
    nDays = DateDiff("d", Now, nYear)
    nHours = DateDiff("h", Now, nYear)
    MsgBox "There are " & nDays & " days from now to the next year." & vbCr & "and there are " & nHours & " hours left."
另外,如果想要在字符串中直接使用日期的话,需要在其前后加上“#”。比如,TimeValue("12:34:56 AM") -> TimeValue("#12:34:56 AM#")

4. 其他函数
Filter(sourcearray, match, include, compare)
-用于从sourcearray数组里筛选出与match指定文字相符的要素,返回新的数组;如果include=False,则不包含match指定的字符。

Split(expression, delimiter, limit, compare)
-按照delimiter分割expression;limit指定分割要素数。

Join(sourcearray, delimiter)
-按照delimiter合成sourcearray里的各要素。

5. 自定义函数
ParamArray的用法:
    Function AllJoin(delim as String, ParamArray SourceStrings())
        AllJoin = Join(SourceStrings, delim)
    End Function

    Sub Test()
        MsgBox AllJoin(",", "English", "Math", "Physics", "Computer", "Music")
    End Sub

posted on 2009-03-07 09:17 koradji 阅读(457) 评论(0)  编辑  收藏 所属分类: Excel VBA


只有注册用户登录后才能发表评论。


网站导航:
 
<2009年3月>
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

导航

统计

常用链接

留言簿(2)

随笔分类

随笔档案

文章分类

文章档案

收藏夹

db2

dos

Groovy

Hibernate

java

WAS

web application

搜索

最新评论

阅读排行榜

评论排行榜