将非空白单元格值从一个工作表复制并粘贴到另一个工作表

时间:2014-07-25 19:55:51

标签: excel vba excel-vba

我正在尝试使用以下代码

将一个工作表中的非空白单元格复制到其他工作表中
Public Sub Copypastenonblanks()
Dim mySheet As Worksheet, myOtherSheet As Worksheet, myBook As Workbook 
Set myBook = Excel.ActiveWorkbook
Set mySheet = myBook.Sheets("Sheet1")
Set myOtherSheet = myBook.Sheets("Sheet2")
mySheet.Range("BK1:BK230").SpecialCells(xlCellTypeConstants).Copy myOtherSheet.Range
("Q2")
End Sub

在工作表列中,BK包含空白单元格,我正在尝试复制非空白和
 粘贴到其他表格,它只粘贴标题,而不是所有数据。

3 个答案:

答案 0 :(得分:1)

您的功能在Excel 2013中对我有用。但是,当内置功能无法产生预期效果时,您可以始终转身并构建您自己的自定义功能(大多数时候,这根本不是很难。

以下是我的表现:

Sub CopyPasteNonBlanks()

    Application.ScreenUpdating = False

    Set wb = ActiveWorkbook
    Set ws1 = wb.Sheets(1)
    Set ws2 = wb.Sheets(2)

    col1 = 63 'Column BK of 1st sheet
    col2 = 17 'Column Q of 2nd sheet

    lastRow1 = ws1.Cells(ws1.Rows.Count, col1).End(xlUp).Row 'Find last row of 1st sheet
    currentRow2 = 2 'Start below headers of 2nd sheet

    For iRow1 = 1 To lastRow1

        If ws1.Cells(iRow1, col1) <> "" Then

            ws2.Cells(currentRow2, col2) = ws1.Cells(iRow1, col1)
            currentRow2 = currentRow2 + 1

        End If

    Next iRow1

    Application.ScreenUpdating = True

End Sub

答案 1 :(得分:0)

这应该做你需要的。

Public Sub Copypastenonblanks()

Dim mySheet As Worksheet
Dim myOtherSheet As Worksheet
Dim myBook As Workbook
Dim irow As Integer
Dim c As Variant

Set myBook = Excel.ThisWorkbook
Set mySheet = myBook.Sheets("Sheet1")
Set myOtherSheet = myBook.Sheets("Sheet2")

irow = 0

Do Until irow = -1
    For Each c In mySheet.Range("BK1:BK230")
        irow = irow + 1

        If c.Value <> "" Then
            myOtherSheet.Cells(irow, 17).Value = c.Value
        Else
            If irow = 230 Then
                irow = -1
            End If
            irow = irow - 1
            GoTo EndofNext
        End If

        If irow = 230 Then
            irow = -1
        End If
EndofNext:
        Next c
    Loop
End Sub

答案 2 :(得分:0)

如果您的目标实际上是复制所有非空白单元格 - 不仅是常量 - 请尝试并替换

mySheet.Range("BK1:BK230").SpecialCells(xlCellTypeConstants).Copy _
myOtherSheet.Range("Q2")

类似
With mySheet.Range("BK1:BK230")
    Union(.SpecialCells(xlCellTypeConstants), .SpecialCells(xlCellTypeFormulas)). _
    Copy myOtherSheet.Range("Q2")
End With