首页 > 解决方案 > 如果 A 列中的单元格不为空,Excel 公式仅在其他工作表中引入行

问题描述

我在一个 Excel 工作簿中有两个工作表,如果 A 列中有数据,我只想取单元格中有数据的行(从工作表 1 到工作表 2)。我在工作表 2 中的公式是=IF('Raw Data'!A2<>"", 'Raw Data'!A2,),但如果没有如第 3 行和第 5 行所示的数据,我实际上根本不希望它引入行。现在它正在引入整行:

样本数据1

样本数据2

您会看到,如果没有数据,它仍会将行带入工作表 2。任何想法如何只引入数据行?

Sub DataInCell()

Dim rw As Long
rw = 2

' Select initial sheet to copy from
Sheets("Raw Data").Select


' Find the last row of data - xlUp will check from the bottom of the spreadsheet up.
FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
' For loop through each row
For x = 2 To FinalRow

       If Cells(x, 1).Value <> 0 Then
        Range("A" & x & ":C" & x).Copy
       Sheets("Sheet1").Select
        NextRow = Cells(Rows.Count, 1).End(xlUp).Row + 1 'Continue incrementing through the rows.
        Cells(NextRow, 1).Select ' Find the next row.
        ActiveSheet.Cells(NextRow, "A").PasteSpecial xlPasteAll ' Paste information.
        Sheets("Raw Data").Select 'Reselect sheet to copy from. Probably uneccessary.
        End If

Next x
End Sub

标签: excelexcel-formula

解决方案


更新第 3 行和第 4 行的工作表名称后,您会看到代码延续了整行。Range(Cells, Cells)如果你想要部分范围,你可以修改使用。

Option Explicit

Sub Non_Blanks()

Dim ms As Worksheet: Set ms = ThisWorkbook.Sheets("Sheet1") '<-- Master Sheet
Dim ns As Worksheet: Set ns = ThisWorkbook.Sheets("Sheet2") '<-- New Sheet

Dim i As Long, MoveMe As Range, LR As Long

For i = 2 To ms.Range("B" & ms.Rows.Count).End(xlUp).Row
    If ms.Range("A" & i) = "*" Then
        If Not MoveMe Is Nothing Then
            Set MoveMe = Union(MoveMe, ms.Range("A" & i))
        Else
            Set MoveMe = ms.Range("A" & i)
        End If
    End If
Next i

If Not MoveMe Is Nothing Then
    LR = ns.Range("A" & ns.Rows.Count).End(xlUp).Offset(1).Row
    MoveMe.EntireRow.Copy
    ns.Range("A" & LR).PasteSpecial xlPasteValuesAndNumberFormats
End If

End Sub

推荐阅读