由于最近需要和数据统计打交道,因此需要将数据库中的东西导入到Excel中进行进一步处理,但是有时候大量运算一些简单的东西,用鼠标操作远不如写代码来的效率高,因此简单学习了一下vba以供提高效率,这里用博客来简单记录一下,以便自己查找。
1.计算Transmission Time
已知表中第G列为传输总大小Size,其中G列为第七列,第I列为传输速率Rate,I列为第9列,将计算结果Transmission Time填入J列(第10列)
Sub getTT()
Dim row&, col1&, col2&, col3&, size#, rate#, tt#
row = 2: col1 = 7: col2 = 9: col3 = 10
Do While Cells(row, 1) <> ""
size = Cells(row, col1)
rate = Cells(row, col2)
tt = size * 8 / rate
Cells(row, col3) = tt
row = row + 1
Loop
MsgBox "done"
End Sub
2.二选一的布尔逻辑到字符串的替换
已知程序的运行结果,0判断为手机,1判断为路由器,这里需要将结果中的0和1替换为字符串 phone和router
代码如下:
Sub classfy()
Dim row&, col&
row = 2: col = 11
Do While Cells(row, 1) <> ""
If Cells(row, col) = 1 Then
Cells(row, col) = "phone"
Else: Cells(row, col) = "router"
End If
row = row + 1
Loop
MsgBox "done"
End Sub
这个程序的易错点是 if else 这种二选一逻辑,在vba中写法为:if 条件1 then 换行,执行语句1,else 冒号 执行语句2, End If
而如果是当条件成立时执行语句1,否则跳过语句1执行时,为 if 条件1 then 不换行 执行语句1,不需要End if
如果是多个条件,则是If 条件1,then 换行,执行语句1,ElseIf 条件2,then换行执行语句2,Else 执行语句3,最后End If
原文:http://www.cnblogs.com/luruiyuan/p/5931193.html