使用Excel VBA将所选数据从一个工作表复制到另一个工作表

时间:2017-07-05 07:50:06

标签: excel vba excel-vba

我正在尝试使用Excel VBA将所选数据从一个工作表复制到另一个工作表。正如您在 0 时在我的图片中看到的那样, test_Point 的值应该写在另一个工作表中。所以我想复制 为0的每个单元格的 test_Point 值。

Sheet1上的源数据:

enter image description here

预期结果将放在Sheet2上:

enter image description here

4 个答案:

答案 0 :(得分:0)

试试这个:

Sub Demo()
    Dim srcWS As Worksheet, destWS As Worksheet
    Dim lastRow As Long, i As Long, rowIndex As Long
    Dim rng As Range

    'change sheet names as required
    Set srcWS = ThisWorkbook.Worksheets("Sheet1")
    Set destWS = ThisWorkbook.Worksheets("Sheet2")
    lastRow = srcWS.Cells(Rows.Count, "A").End(xlUp).Row
    rowIndex = 1

    With srcWS
        For Each rng In .Range("B2:B" & lastRow)
            If rng.Value = 0 Then
                destWS.Range("A" & rowIndex).Value = rng.Offset(0, -1).Value
                rowIndex = rowIndex + 1
            End If
        Next rng
    End With
End Sub

答案 1 :(得分:0)

这应该可行,只需将工作表/工作簿的名称更改为您正在使用的任何内容,同时也必须打开两个工作簿才能运行此代码。

Option Explicit

Sub Copydata()

Dim i As Long, j As Long, lLr As Long
Dim wsSource As Worksheet, wsTarget As Worksheet
Dim wbSource As Workbook, wbTarget As Workbook

    Set wbSource = Workbooks("WbSource") 'sets source workbook
    Set wbTarget = Workbooks("WbTarget") 'sets target workbook

Set wsSource = wbSource.Worksheets("SourceSheet") 'sets source worksheet
Set wsTarget = wbTarget.Worksheets("TargetSheet") 'sets target worksheet

lLr = wsSource.Range("B" & Rows.Count).End(xlUp).Row

j = 1

For i = 2 To lLr

    If wsSource.Range("b" & i) = 0 Then

        wsTarget.Range("a" & j).Value = wsSource.Range("A" & i)
        wsTarget.Range("a" & j).NumberFormat = "0.0"
        j = j + 1

    End If

Next i

End Sub

答案 2 :(得分:0)

Таке看下面的例子:

Option Explicit

Sub Test()

    Dim rSrc As Range
    Dim rDst As Range

    ' First cell with source data which is to be evaluated
    Set rSrc = ThisWorkbook.Sheets("Sheet1").Range("B2")
    ' First destination cell where to put result
    Set rDst = ThisWorkbook.Sheets("Sheet2").Range("A1")

    Do
        ' Check if source cell is empty
        If rSrc = "" Then Exit Do
        ' Check if source cell is 0
        If rSrc = 0 Then
            ' Copy value of the cell to the left to the destination
            rDst.Value = rSrc.Offset(0, -1).Value
            ' Move destination down
            Set rDst = rDst.Offset(1, 0)
        End If
        ' Move source down
        Set rSrc = rSrc.Offset(1, 0)
    Loop

End Sub

答案 3 :(得分:-1)

我的工作表名为“aaaa”,第二名名为“bbbb”。

在“bbbb”中,我将函数放在一个单元格中:

=IF(aaaa!A1<10; "dog"; "cat")

如果值小于10,这将在单元格A1中查看第一个,然后在单元格中显示一些文本作为第二个工作表。

您需要在功能中更改条件,以便为您提供所需的结果。

这是你在找什么?

以下是一些在访问VBA中的值时可能有用的链接