Excel根据单元格值复制到特定工作表

时间:2017-05-05 12:03:18

标签: excel vba excel-vba

我目前正在尝试将文字从我的封面复制到变体表。

我想要的是将单元格J19,J20,J21复制到不同页面的单元格A1,B1,C1。 J19决定要复制到哪个工作表,因为每个代理商都有自己的工作表,其中有一个宏将代理名称拉入到J19的数据验证中。

J19 =代理商名称

J20 =假期开始日期

J21 =假期结束日期

如何更改Set wsDestin = Sheets("Agent1")以便查看J19以确定目标单元格。

Sub CopyColumnP()
    Dim wsSource As Worksheet
    Dim wsDestin As Worksheet
    Dim lngDestinRow As Long
    Dim rngSource As Range
    Dim rngCel As Range

    Set wsSource = Sheets("Front")
    Set wsDestin = Sheets("Agent1")

    With wsSource

        Set rngSource = .Range(.Cells(19, "J"), .Cells(.Rows.Count, "J").End(xlUp))
    End With

    For Each rngCel In rngSource
        If rngCel.Value = "Design" Then
            With wsDestin
                lngDestinRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
                rngCel.EntireRow.Copy Destination:=wsDestin.Cells(lngDestinRow, "A")
            End With
        End If
    Next rngCel
    End Sub

1 个答案:

答案 0 :(得分:1)

这很容易:

Set wsDestin = ThisWorkbook.Worksheets(wsSource.Range("J19").Value)

要检查工作表是否存在,请使用以下方法防止错误:

On Error Resume Next
    Set wsDestin = ThisWorkbook.Worksheets(wsSource.Range("J19").Value)
    If Not Err.Number = 0 Then 
        MsgBox "Sheet '" & wsSource.Range("A1").Value & "' not found."
        Exit Sub
    End If
On Error GoTo 0

或者,如果J19不包含目标工作表名称,但您需要根据J19的值选择工作表,请使用:

Select Case wsSource.Range("J19").Value
    Case "AAA" 'if value of J19 is AAA select sheet A
        Set wsDestin = Sheets("A")

    Case "B", "C" 'if value of J19 is B or C select sheet BC
        Set wsDestin = Sheets("BC")

    Case Else
        MsgBox "no corresponding worksheet found."
End Select