标签:VBA
这是在www.vbaexpress.com中看到的一个示例,个人觉得代码很有代表性,特辑录于此,与大家共享。
示例数据如下图1所示。
想要删除行和列中的空单元格,变成如下图2所示。
可以使用下面的VBA代码:
Sub DeleteEmpty()
Dim r As Long, c As Long
Dim rLast As Range, rData As Range, rEnd As Range
Application.ScreenUpdating = False
With ActiveSheet
Set rLast = .Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False)
Set rData = Range(.Cells(1, 1), rLast)
With rData
'删除空字符串使之成为真的空单元格
.Replace What:="", Replacement:="###", LookAt:=xlPart
.Replace What:="###", Replacement:="", LookAt:=xlPart
'删除空列
For c = .Columns.Count To 1 Step -1
If Application.WorksheetFunction.CountBlank(.Columns(c)) = .Rows.Count Then
.Columns(c).Delete
End If
Next c
'删除空行
For r = .Rows.Count To 1 Step -1
If Application.WorksheetFunction.CountBlank(.Rows(r)) = .Columns.Count Then
.Rows(r).Delete
End If
Next r
End With
Set rLast = .Cells.Find(What:="*", _
After:=Range("A1"), _
LookAt:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False)
Set rData = Range(.Cells(1, 1), rLast)
'向上移动数据
For c = 1 To rData.Columns.Count
Set rEnd = rData.Columns(c).Cells(.Rows.Count, c).End(xlUp)
On Error Resume Next
Range(.Cells(1, c), rEnd).SpecialCells(xlCellTypeBlanks).Delete shift:=xlUp
On Error GoTo 0
Next c
End With
Application.ScreenUpdating = False
End Sub
若要变成下图3所示的样子,即将数据全部放置到列A中。
代码如下:
Sub test()
Dim rng As Range, rCell As Range, var As Variant, x As Long, rCount As Long
Set rng = Sheet1.UsedRange
With rng
.Replace "", "|"
.Replace "|", ""
Set rng = .SpecialCells(xlCellTypeConstants)
rCount = .Cells.Count
End With
ReDim var(rCount - 1)
For Each rCell In rng
var(x) = rCell
x = x + 1
Next rCell
Range("A1").Resize(rCount) =
Application.Transpose(var)
End Sub
上面的代码移动的数据并不是按每列逐列将数据移动到列A中的,而是逐行将数据放置到列A中的。要想逐列移动数据到列A中,达到如下图4所示的效果。
代码如下:
Sub test()
Dim rng As Range, var As Variant, oVar() As Variant
Dim r As Long, c As Long, z As Long
Set rng = Sheet1.UsedRange
ReDim oVar(Application.CountIf(rng, "?*") - 1)
var = rng.Value
For c = 1 To UBound(var, 2)
For r = 1 To UBound(var)
If Len(var(r, c)) > 0 Then
oVar(z) = var(r, c): z = z + 1
End If
Next r
Next c
Range("A1").Resize(UBound(oVar) + 1) = Application.Transpose(oVar)
End Sub
欢迎在下面留言,完善本文内容,让更多的人学到更完美的知识。