【问题标题】:Excel VBA - copy only row-range that contains specific value in column on a different workbookExcel VBA - 仅复制在不同工作簿的列中包含特定值的行范围
【发布时间】:2018-05-21 08:17:45
【问题描述】:

如果 DA 列中的单元格包含特定值,我想创建一个复制行范围的宏。

例如:

如果列 DA10 包含值 3-incompletion,N10 不包含任何内容,CI10 不包含任何内容 - 那么宏应将单元格 F10、H10 和 DA10 复制到工作簿 reportWB强>。我不知道该怎么做。

到目前为止的进展(感谢 Shai - 我仍然愚蠢地让它发挥作用):

Sub insertINCOMPLETION()

Dim dataWB As Workbook
Dim reportWB As Workbook
Dim workB As Workbook
Dim incomplRNG As Range
Dim LastRow6 As Long
Dim LastRow7 As Long

For Each workB In Application.Workbooks
    If Left(workB.Name, 5) = "15B2" Then
        Set dataWB = workB
        Exit For
    End If
Next

    If Not dataWB Is Nothing Then
        Set reportWB = ThisWorkbook

    With reportWB.Sheets("getDATA")
        LastRow6 = .Cells(.Rows.Count, "B").End(xlUp).Offset(1).Row
    End With

With dataWB.Sheets("Data")
    LastRow7 = .Cells(.Rows.Count, "F").End(xlUp).Row

     If InStr(.Range("DA" & LastRow7).Value2, "3-Incompletion") > 0 And _
        Trim(.Range("N" & LastRow7).Value2) = "" And _
        Trim(.Range("CI" & LastRow7).Value2) = "" Then
        Set incomplRNG = Application.Union(.Range("F8:F" & LastRow7), .Range("H8:H" & LastRow7), .Range("DA8:DA" & LastRow7))
        incomplRNG.Copy
        reportWB.Sheets("getDATA").Range("B" & LastRow6).PasteSpecial xlPasteValues
    End If
End With
End If
End Sub

还是不行。检查 DA 列后结束。

【问题讨论】:

  • 将单元格与"3-incompletion" 进行比较的代码部分在哪里?你可以使用If InStr(.Cells(10, "AD"), "3-incompletion") > 0 Then
  • 我并不是很喜欢“如果”——之前尝试对数据进行排序,只复制排序后的区域,但因为它不起作用而尴尬地发布它......我会看看我是否可以实施你的建议。另外:感谢您编辑我所有的帖子。每次我提交问题时,我都认为您不必编辑它:-D - 2 分钟后...

标签: vba excel


【解决方案1】:

您需要添加将单元格文本与“3-incompletion”进行比较的代码部分。你可以使用InStr函数来实现。

With dataWB.Sheets("Data")
    ' === not sure why you want to look for the last row ??? ===
    'LastRow7 = .Cells(.Rows.Count, "F").End(xlUp).Row

    ' compare the value in row 10 (as in your post example)
    LastRow7 = 10

     If InStr(.Range("AD" & LastRow7).Value2, "3-incompletion") > 0 And _
        Trim(.Range("AD" & LastRow7).Value2) = "" And _
        Trim(.Range("CI" & LastRow7).Value2) = "" Then
        Set incomplRNG = Application.Union(.Range("F8:F" & LastRow7), .Range("H8:H" & LastRow7), .Range("DA8:DA" & LastRow7))
        incomplRNG.Copy
        reportWB.Sheets("getDATA").Range("B" & LastRow6).PasteSpecial xlPasteValues
    End If          
End With

【讨论】:

  • 我查找了最后一行,因为我试图对其进行排序并复制整个排序后的数据。我试试,谢谢!
  • @Bluesector 我的代码适用于第 10 行,但您可以轻松修改它,或将其添加到 For 循环中
  • 谢谢,由于宏目前非常庞大,仍在尝试使其工作。您能否快速解释一下如何添加两个条件?宏还必须检查列 N8:Nxxx & CI8:CIxxx 是否为空白。仅当这两列都是空白且 DA 列中的值为 3-incompletion 时,宏才应复制该范围。有没有像添加另一个值这样简单的解决方案?
  • @Bluesector 查看编辑后的代码,看看这是不是你的意思
  • 你能看看我在上面的帖子吗?我添加了编辑后的代码,但不知何故,With reportWB.Sheets("getDATA") 行被突出显示。我还发现了“代码”按钮……这对我来说容易多了。
猜你喜欢
  • 2017-08-24
  • 2019-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-15
  • 2020-03-14
  • 1970-01-01
相关资源
最近更新 更多