一直没有接触过VBA编程,最近工作中遇到一个问题迫使我研究了一下简单的VBA编程。原来效果还是不错,通过一段VBA代码的确帮我做了大量对excel文档的重复的拷贝、粘贴工作。
简单的理解VBA脚本就是一种可以在excel中运行的宏脚本,他在VB语法的基础上提供了很多针对excel操作的对象模型API,简单看一下他的帮助文档就可以大概了解他是如何来操作excel的。其实如果简单的操作,你直接在excel菜单里录制一下宏,excel会自动为你生成一段VBA脚本的。打开visual basic editer就可以编辑他。如果你从来没有写过VBA脚本,可以录制一下手工操作来参考他生成的代码,按照自己的要求修改。
下面是我遇到的问题:我有若干的文档中,有很多下面这样格式的表格数据
1-1-1-1
1-1-1-1-1
1-1-1-1-2
1-1-1-1-3
1-1-1-1-4
上级变态要求改成下面的样子的格式:
4
1
1
4
1
2
4
1
2
1
4
1
2
2
完成这个工作如果不写脚本来完成,那就只有手工的完成,十多个文档不知道会做多久这样无聊重复的工作。最后经过简单的研究写了vba脚本完成了这个工作。脚本的工作应该先把上面的一个格子辟分成5个,然后把1-1-1-1-3依短线分开分别填到辟分出来的五个格子里。
下面是的脚本代码,不要被这么长的代码吓倒,其实很多代码都是用录制宏的办法生成的,不会写某个操作的代码,最好的办法就是录制一段宏生成代码然后再来看。比如选择几个格子然后拷贝,粘贴到另一个地方。看看生成的代码基本就可以看懂了。如果你的工作中遇到了这样需要大量修改excel文档的工作,可以考虑一下写一段vba脚本来完成繁琐重复的劳动。
Sub splitCell(beginRowId, endRowId)
Dim begRange, endRange, endRange2
begRange = "A" & beginRowId
endRange = "A" & endRowId
endRange2 = "E" & endRowId
Range(begRange & ":" & endRange).Select
Selection.ClearFormats
Range(begRange & ":" & endRange2).Select
Selection.Borders(xlDiagonalDown).LineStyle = xlNone
Selection.Borders(xlDiagonalUp).LineStyle = xlNone
With Selection.Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideVertical)
.LineStyle = xlDash
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection.Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlThin
.ColorIndex = xlAutomatic
End With
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlTop
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.MergeCells = False
End With
Selection.NumberFormatLocal = "@"
End Sub
Sub ParseSplitTestId(cellRowId)
'parse id String use "-"
Dim tmpStr, myArr
tmpStr = Cells(cellRowId, 1).Value
myArr = Split(tmpStr, "-", 5)
For intI = 0 To UBound(myArr)
'MsgBox "--" & myArr(intI)
'Range("A" & (cellRowId + intI)).Value = myArr(intI)
Cells(cellRowId, 1 + intI).Value = CStr(myArr(intI))
Next
End Sub
Sub ParseSplitStr(beginRowId, maxRowId)
Dim count, tmpId, tmpStr
count = maxRowId - beginRowId + 1
For intI = 0 To count
tmpId = beginRowId + intI
'tmpStr = Cells(tmpId, 1).Value
'MsgBox (tmpStr = "")
'If tmpStr = "" Then
' Exit For
'End If
ParseSplitTestId (tmpId)
Next
End Sub
Sub ProcessOneFile(filename, maxRowId)
Dim beginRowId
beginRowId = 8
Windows(filename).Activate
Worksheets(2).Select
Call splitCell(beginRowId, maxRowId)
Call ParseSplitStr(beginRowId, maxRowId)
Windows(filename).ActivateNext
MsgBox filename & " - process sucess!"
End Sub