在Excel VBA中使用PasteSpecial跳过空白值

时间:2017-05-25 16:25:52

标签: excel vba

我尝试过在网上找到的各种解决方案,但还没有运气。这是我的VBA代码,用于从大约30张纸张中复印单元格并将它们全部粘贴到一张纸上。每张工作表都有4列中的公式,如果另一张表中有值,则显示值。像这样:

=IF(Sheet1!A2<>"", Sheet1!A2, "")

然后我在我希望输出的页面上运行我的宏:

Sub SummurizeSheets()
Dim ws As Worksheet

Application.ScreenUpdating = False
Sheets("Summary").Activate

For Each ws In Worksheets
    If ws.Name <> "Summary" And ws.Name <> "Sheet1" Then
        ws.Range("A2:D5406").Copy
        Worksheets("Summary").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial (xlPasteValues), SkipBlanks:=True
    End If
Next ws
End Sub

输出结果会产生大量空白单元格后的实际值。

我尝试将“SkipBlanks”变体放在那里,但那不是解决方案。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我在excelforum.com上回答了这个问题,我想我会在这里发布解决方案,以防其他人帮忙。

Sub SummurizeSheets()
Dim ws As Worksheet

Application.ScreenUpdating = False
Sheets("Summary").Activate

For Each ws In Worksheets
    If ws.Name <> "Summary" And ws.Name <> "Sheet1" Then
        ws.Range("A2:D5406").Copy
        Worksheets("Summary").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial Paste:=xlPasteValues, SkipBlanks:=False
    End If
Next ws

'Try inserting this line
'***********************************************************************

Worksheets("Summary").Select

'************************************************************************
'Find the last used row in column 1
LR = Cells(Rows.Count, 1).End(xlUp).Row

'Insert a formula in column E to return the row number of any non blank row
Range("E1:E" & LR).FormulaR1C1 = "=IF(RC[-4]="""","""",ROW())"

'Copy Paste Values to remove the formula
Range("E1:E" & LR).Value = Range("E1:E" & LR).Value

'Sort your data
ActiveWorkbook.Worksheets("Summary").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Summary").Sort.SortFields.Add Key:=Range("E1:E" & LR) _
    , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Summary").Sort
    .SetRange Range("A1:E" & LR)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

'Clear Column E
Range("E1:E" & LR).ClearContents
Range("A1").Select
End Sub