VB初试

上次在知乎上看到一个帖子,如何起名字,有个答案印象深刻,决定动手试一试,采用excel,蛮好玩的。
示意图

A、B两列是从诗经中截取的,C、D两列随机取AB两列的1-2个字组合而成。
两个控件绑定的宏函数如下:

Sub two_word()
Dim first_name As String
Dim second_name As String
Dim temp As String
Dim temp2 As Integer
Dim i As Integer
For i = 1 To 24

   first_name = Mid(Sheets(1).Cells(i, 1), Application.RandBetween(1, Len(Sheets(1).Cells(i, 1))), 1)
   second_name = Mid(Sheets(1).Cells(i, 2), Application.RandBetween(1, Len(Sheets(1).Cells(i, 2))), 1)
   'first_name = StrConv(first_name, vbFromUnicode)
   'second_name = StrConv(second_name, vbFromUnicode)
   Sheets(1).Cells(i, 3) = first_name & second_name
'MsgBox first_name, vbOKOnly
'MsgBox second_name, vbOKOnly
Next i
End Sub

Sub three_word()
Dim first_name As String
Dim second_name As String
Dim temp As String
Dim temp2 As Integer
Dim i As Integer
For i = 1 To 24

   first_name = Mid(Sheets(1).Cells(i, 1), Application.RandBetween(1, Len(Sheets(1).Cells(i, 1))), 2)
   second_name = Mid(Sheets(1).Cells(i, 2), Application.RandBetween(1, Len(Sheets(1).Cells(i, 2))), 1)
   'first_name = StrConv(first_name, vbFromUnicode)
   'second_name = StrConv(second_name, vbFromUnicode)
   Sheets(1).Cells(i, 4) = first_name & second_name
'MsgBox first_name, vbOKOnly
'MsgBox second_name, vbOKOnly
Next i
End Sub

遇到的坑:
1、Midb函数将中文转化为ascii码了,导致输出的名字全是乱码,应该使用mid函数,关于excel的编码转化,可以参考,主要使用StrConv函数:http://blog.chinaunix.net/uid-7374279-id-3934228.html
2、RandBetween是excel前台sheet页可调用的函数,在VBA中应写成:Application.RandBetween调用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值