在工作中,常需帮用户处理一些大批量的作重复性操作数据,如果为这种一次的工作写一支程序,是比较耗时间的.而这些数据都是在EXCEL中进行,因此便想到了,VBA(Visual Basic Application),是OFFICE中自动执行任务和可编程性,也可称作宏。
但是如果因为没有VBA的基础,所以从开头始写比较费时间的,于是我采用录制宏的方式,将第一次的操作记录下,保存后,再对这个宏进行修改成循环的语句。
以下就是我对一个5000多行数据进行处理的VBA.
Sub Macro1()
'
' Macro1 Macro ,生成EPL之MI_GL文件.
' 宏由 pc2119 录制,时间: 2006-2-23
'
Dim i As Integer
Dim j As Integer
Dim str As String
Dim str_tmp As String
Dim HD_cnt As Integer '记录GL no开始的行号
Dim Ln_cnt As Integer '记录处理到的行号
Dim CP_cnt As Integer '记录一行UPG需COPY几次
Dim Deal_cnt As Integer
Dim Car_no
Dim Title_no
'定义数据处理的总共行数.
i = 0
'定义数据处理起始的行
Ln_cnt = 11
HD_cnt = 10
Car_no = Array(61, 62, 63, 64, 65, 67)
Title_no = Array("L", "M", "N", "O", "P", "Q")
While i < 5000
'标记一个UPG是否处理完成,进行计数.
'先计算需COPY的UPG行数/通过判断VC CODE是否有值.
Deal_cnt = 0
CP_cnt = 0
Do
str = Title_no(Deal_cnt) + CStr(Ln_cnt)
Range(str).Select
str_tmp = Trim(ActiveCell.Value)
If Len(str_tmp) > 0 Then
CP_cnt = CP_cnt + 1
End If
Deal_cnt = Deal_cnt + 1
Loop Until Deal_cnt > 5
CP_cnt = CP_cnt - 1
'COPY 指定行数UPG行资料
j = Ln_cnt
Deal_cnt = 0
While CP_cnt > Deal_cnt
'选择目标行并COPY
str = CStr(Ln_cnt) + ":" + CStr(Ln_cnt)
Rows(str).Select
Selection.Copy
'处理的行数加1
Ln_cnt = Ln_cnt + 1
'在COPY的行下插入COPY的行
str = CStr(Ln_cnt) + ":" + CStr(Ln_cnt)
Rows(str).Select
Selection.Insert Shift:=xlDown
Deal_cnt = Deal_cnt + 1
Wend
'填充GLNO与UPG资料
Deal_cnt = 0
Ln_cnt = j
Do
str = Title_no(Deal_cnt) + CStr(Ln_cnt)
Range(str).Select
str_tmp = Trim(ActiveCell.Value)
'If Not (IsNull(ActiveCell.Value) Or IsEmpty(ActiveCell.Value)) Then
If Len(str_tmp) > 0 Then
'对VC不足2位的,补足两位
If Len(str_tmp) = 1 Then str_tmp = "0" + CStr(str_tmp)
'给该行的GLNO赋值
str = "A" + CStr(Ln_cnt)
Range(str).Select
ActiveCell.FormulaR1C1 = "=RC[1]&" + CStr(Car_no(Deal_cnt))
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Application.CutCopyMode = False
'给该行UPG赋值.
str = "E" + CStr(Ln_cnt)
Range(str).Select
str_tmp = CStr(ActiveCell.Value) + str_tmp
str = "D" + CStr(Ln_cnt)
Range(str).Select
ActiveCell.Value = CStr(str_tmp)
Ln_cnt = Ln_cnt + 1
End If
Deal_cnt = Deal_cnt + 1
Loop Until Deal_cnt > 5
i = i + 1
'Ln_cnt = Ln_cnt + 1
Wend
End Sub