繁体   English   中英

根据特定条件将特定单元格值从一个工作表复制粘贴到另一个工作表

[英]Copy paste specific cell values from one work sheet to another based on a specific criteria

我已经有一段时间没有做任何类型的编码了,所以我很生疏。 我正在尝试编写一些 VBA 代码,以便在 excel 工作表中单击一个按钮时,它将检查同一工作簿中的另一个工作表和特定单元格值的副本。 这是基于其中一列中的标准(我数了第 15 列); 我可能应该补充一点,数据在表格中。 如果该行符合第 15 列的指定条件,则使用按钮将特定列复制到工作表中。

我确实有一些代码,但我知道其中缺少很多东西。

不胜感激,我在正确的轨道上吗? 任何人都可以在那里提供帮助,我可以获得有关我需要使用的编码的更多信息和提示。 不确定是否有使用表格的简单方法?

Private Sub CommandButton1_Click()

''This will count how many rows are populated in the table''
a = Worksheets("Billable").Cells(Rows.Count, 1).End(xlUp).Row

''Loop will run from row 6 to the last row (Row 6 is the first row in table)''
For i = 6 To a
    ''If statement which will check the status column for Detailed Estimate Submitted > column 15''
    If Worksheets("Billable").Cells(i, 15).Value = "Detailed Estimate Submitted" Then
      Worksheets("Billable").Rows(i).Copy
      Worksheets("PM_Forecast").Activate
      b = Worksheets("PM_Forecast").Cells(Rows.Count, 1).End(xlUp).Row
      Worksheets("PM_Forecast").Cells(a + 1, 1).Select
      ActiveSheet.Paste
    End If
Next

Application.CutCopyMode = False

End Sub

表格示例: - 如果它们满足状态列中的特定条件,我只需要复制超过 3 个列

表格标题

我无法发表评论,所以我将通过这个答案提出问题:

您的变量 b 当前未使用,我认为它应该在这一行: Worksheets("PM_Forecast").Cells(b + 1, 1).Select但您写的是 a 而不是 b。

这是否解决了您当前的问题?

你没有回答我关于格式粘贴的问题......

因此,请测试以经典方式粘贴的下一个代码。 但没有选择和声明所有使用的变量:

Private Sub CommandButton1_Click()
 Dim shB As Worksheet, shPM As Worksheet, lastRowB As Long, lastRowPM As Long
 Dim i As Long, lastCol As Long

 Set shB = Worksheets("Billable")
 Set shPM = Worksheets("PM_Forecast")

 lastRowB = Worksheets("Billable").Cells(Rows.Count, 1).End(xlUp).row

 'Loop will run from row 6 to the last row (Row 6 is the first row in table)''
 For i = 6 To lastRowB
    If shB.Cells(i, 15).Value = "Detailed Estimate Submitted" Then
        lastCol = shB.Cells(i, Columns.Count).End(xlToLeft).Column
        lastRowPM = shPM.Cells(Rows.Count, 1).End(xlUp).row
        shB.Range(shB.Range("A" & i), shB.Cells(i, lastCol)).Copy _
                                   shPM.Cells(lastRowPM + 1, 1)
    End If
 Next
 Application.CutCopyMode = False
End Sub

对于使用变体的数组,您只能声明一个新变量Dim arr As Variant并替换此部分:

shB.Range(shB.Range("A" & i), shB.Cells(i, lastCol)).Copy _
                                   shPM.Cells(lastRowPM + 1, 1)

有了这个:

arr = shB.Range(shB.Range("A" & i), shB.Cells(i, lastCol)).Value
shPM.Cells(lastRowPM + 1, 1).Resize(, UBound(arr, 2)).Value = arr

然后,删除代码行Application.CutCopyMode = False 不再需要,因为不使用剪贴板 memory...

并在模块顶部使用Option Explicit 当代码变得复杂时,它将为您节省很多次。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM