如何使用vba在Excel中制作蒙版?

时间:2015-12-24 03:27:24

标签: excel vba mask

我在Excel中创建了一个用户表单,可以说3个字段。 name1brc1tmx1。用户可以在字段tmx1中输入1到9999之间的任何数字。我希望他点击发送按钮的时间将以下0000的屏蔽号码发送到另一个ecxel已命名data.xls例如,如果用户在字段tmx1 21 中键入,我希望程序发送 0021 ,如果他输入 321 发送 0321 如果它是4个数字那么它就可以了,依此类推。

我的部分代码如下:

Private Sub cmdSend_Click()
Workbooks.Open Filename:="Z:\Tameio\data.xls"
Range("A1").Select
ActiveCell.End(xlDown).Select
lastrow = ActiveCell.Row

Cells(lastrow + 1, 1).Value = name1.Text
Cells(lastrow + 1, 2).Value = brc1.Text
Cells(lastrow + 1, 3).Value = tmx1.Text
Range("A1").Select
ActiveWorkbook.Close SaveChanges:=True

1 个答案:

答案 0 :(得分:3)

您可以使用Format功能进行屏蔽。以此函数存根为例:

Public Function Masking(Data As Integer) As String
    Masking = Format(Data, "0000")
End Function

Sub Test_Masking()
    Debug.Print Masking(1)
    Debug.Print Masking(12)
    Debug.Print Masking(123)
    Debug.Print Masking(1234)
    Debug.Print Masking(12345)
End Sub

结果:

0001
0012
0123
1234
12345

将其应用于您的案例:

Private Sub CommandButton1_Click()
    Workbooks.Open Filename:="Z:\Tameio\data.xls"
    Range("A1").Select
    ActiveCell.End(xlDown).Select
    lastrow = 10  ' change this to whatever you prefer

    Cells(lastrow + 1, 1).Value = name1.Text
    Cells(lastrow + 1, 2).Value = brc1.Text
    Cells(lastrow + 1, 3).Value = "'" & Format(tmx1.Text, "0000")
    Range("A1").Select
    ActiveWorkbook.Close SaveChanges:=True
End Sub

编辑:

根据Mat's Mug的优秀建议,这是一个更通用的格式化功能:

Public Function Masking(Data As Integer, TotalLengthWithZeroPad As Integer) As String
    Masking = Format(Data, String(TotalLengthWithZeroPad, "0"))
End Function

Sub Test_Masking()
    Dim totallength As Integer
    totallength = 10 ' how long will our string's total length be?
    Debug.Print Masking(1, totallength)
    Debug.Print Masking(12, totallength)
    Debug.Print Masking(123, totallength)
    Debug.Print Masking(1234, totallength)
    Debug.Print Masking(12345, totallength)
End Sub

结果

0000000001
0000000012
0000000123
0000001234
0000012345