【问题标题】:Wanting to copy from one sheet to another, based on values in one column想要根据一列中的值从一张纸复制到另一张纸
【发布时间】:2021-12-29 17:47:58
【问题描述】:

我有一份估价单和一张发票。我正在尝试编写代码来搜索估算表中的单位列(“L”)。找到数字后,将不同列(“A”)中的描述复制到特定范围内的发票表中。我能够让搜索循环遍历 L 列,它可以确定数字是否> 0。它甚至会将第一个描述复制到发票上。但是,它不会复制任何内容。我正在寻求帮助。到目前为止,这是我的代码。

Sub CopyToInvoice()
    Dim rng As Range
    Dim i As Long
    Dim a As Long
    Dim rng_dest As Range
    Application.ScreenUpdating = False
    i = 1
    Set rng_dest = Sheets("Estimate").Range("L5")
    'Find first cell with value in column L on sheet Estimate
    Range("L5").Select
    Do Until WorksheetFunction.CountA(rng_dest.Rows(i)) = 100
    i = i + 1
    Set rng = Sheets("Invoice").Range("C22:C36")
    'Copy rows containing values to sheet Invoice
    For a = 1 To rng.Rows.Count
      If ActiveCell.Value > 0 Then
       Sheets("Estimate").Range("A5").Copy Sheets("Invoice").Range("C22")
      End If
        'Step down 1 row from present location
       ActiveCell.Offset(1, 0).Select
       i = i + 1
     Next a
  Application.ScreenUpdating = True
  Loop
End Sub

【问题讨论】:

  • 如果这需要查找,应该涉及 4 列,每个工作表 2 列。为简单起见,我们将它们分别设为源和目标的 A、B 和 C、D。您遍历目标 C 以在源 A 中查找匹配项。如果找到,则将源 B 复制到目标 D。与您的代码相关,您遍历 Invoice C 以在 Estimate L 中查找匹配项。如果找到,请将Estimate A 复制到Invoice ?。您的代码暗示?C,但这会覆盖C 中的值(这是有效的)。你确定你要这么做吗?请确认或建议另一列。
  • 发票 C 为空白。我想根据 Estimate L 中的条目完成 Invoice,从 Estimate A 复制到 Invoice C。

标签: excel vba copying


【解决方案1】:

如果满足条件,则从另一列写入

Option Explicit

Sub CopyToInvoice()
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    ' Source
    Dim sws As Worksheet: Set sws = wb.Worksheets("Estimate")
    Dim slRow As Long: slRow = sws.Cells(sws.Rows.Count, "L").End(xlUp).Row
    If slRow < 5 Then Exit Sub ' no data in column range
    
    ' Destination
    Dim dws As Worksheet: Set dws = wb.Worksheets("Invoice")
    Dim dCell As Range: Set dCell = dws.Range("C22")
    
    Application.ScreenUpdating = False
    
    Dim r As Long
    
    For r = 5 To slRow ' rows in 'L'
        If IsNumeric(sws.Cells(r, "L").Value) Then ' numeric
            If sws.Cells(r, "L").Value > 0 Then ' check 'L>0'
                dCell.Value = sws.Cells(r, "A").Value ' write 'A' to destination
                Set dCell = dCell.Offset(1) ' next destination
            'Else ' L <= 0
            End If
        'Else ' not numeric
        End If
    Next r
    
    Application.ScreenUpdating = True

    MsgBox "Data copied.", vbInformation

End Sub

【讨论】:

  • 效果很好!!非常感谢!
【解决方案2】:

您将在每次迭代中粘贴到发票表中的同一行。

更换你的线路:

Sheets("Estimate").Range("A5").Copy Sheets("Invoice").Range("C22")

Sheets("Estimate").Range("A" &amp; 4 + a).Copy Sheets("Invoice").Range("C" &amp; 21 + a)

【讨论】:

  • 使用F8逐行运行代码将帮助您解决这些难题。在每一行之后查看 vba 在 Excel 中的作用。
  • 我正在使用“Step-in”来观察会发生什么。根据您建议的更改,复制的值是“0”而不是 A 列中的描述。它会跳过与空行相同的数字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-14
  • 1970-01-01
相关资源
最近更新 更多