2017-05-05 157 views
0

我正在尝试将文本从我的工作表复制到变体工作表。Excel根据单元格值复制到特定工作表

我想要的是将单元格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 
+0

单元格(“J19”)。值 – Luuklag

+0

真的那么简单吗?我认为这会更复杂@Luuklag –

回答

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 
+0

'运行时错误'9': 下标超出范围 –

+0

如果即时更正,将取代'J19'的内容?我想让代码看看'J19'来决定从'J19,J20,21'复制和粘贴数据到'J19'中表单名称的'A1,A2,A3'的数据。 –

+0

左边的等号将得到等号右边的值。您可能想在此明确引用工作簿。 – Luuklag

相关问题