【问题标题】:Copy from one sheet to another workbook based on multiple criteria VBA Excel基于多个标准 VBA Excel 从一张工作表复制到另一个工作簿
【发布时间】:2017-02-14 09:10:54
【问题描述】:

我有两个不同的工作簿,我想从其中一个中复制基于多个标准的特定值。

在本例中,我将调用每个工作簿 wb1 和 wb2。文章末尾会有共享的 wb 链接作为示例,以使其看起来更清晰..

所以在 wb1 中,我有一个名称列表,这些名称在 wb2 中也有自己的工作表。 当我打开 wb1 时,我想将名为“NPS”的单元格下的值复制到 wb2 中具有相同名称的每个工作表中,在 wb2 中,我有不同的月份和一些其他我必须手动添加的变量。所以我想要它做的是将 NPS 中的值复制到 NPS 下的数据中,并将其与 wb1 中也提到的同一月份匹配。

到目前为止我所拥有的是这段代码,但它并没有真正实现它。因为我在这部分设置 sh2 = wb2.Sheets(c.Value) 上得到“订阅超出范围”。我的猜测是,即使它的命名完全相同,它也无法通过值来识别工作表。

Sub NPS()
Dim sh1 As Worksheet, sh2 As Worksheet, c As Range, wb2 As Workbook, fn As Range
Set sh1 = ThisWorkbook.ActiveSheet
Set wb2 = Workbooks.Open("F:\Excel\Chef\NPS Samtal 777 agentnivå.xlsx")
    For Each c In sh1.Range("C8", sh1.Cells(Rows.Count, 3).End(xlUp))
        Set sh2 = wb2.Sheets(c.Value)
        Set fn = sh2.Rows(24).Find(sh1.Range("B5").Value, , xlValues, xlWhole)
        If Not fn Is Nothing Then
               fn.Offset(1) = sh1.Range("E5").Value
        End If
    Next
End Sub

WB1:https://docs.google.com/spreadsheets/d/14CyC2CQWWH-Bxifw2EBni0Uj2YjlN-kIUVki2rle3LA/edit#gid=1398323909

WB2:https://docs.google.com/spreadsheets/d/1vcfnluE_PSm5dEEeHuBPA9XRoP-VPQRk3YDE7ONS-NE/edit?usp=sharing

如果有人有任何建议,我将非常高兴。

//问候丹尼尔

【问题讨论】:

    标签: excel criteria copy-paste multiple-conditions vba


    【解决方案1】:

    Excel 似乎在错误文件中查找工作表。您需要在插入值之前激活正确的工作簿。像这样:

    Sub NPS()
    Dim sh1 As Worksheet, sh2 As Worksheet, c As Range, wb2 As Workbook, fn As Range
    Set sh1 = ThisWorkbook.ActiveSheet
    Set wb2 = Workbooks.Open("F:\Excel\Chef\NPS Samtal 777 agentnivå.xlsx")
        For Each c In sh1.Range("C8", sh1.Cells(Rows.Count, 3).End(xlUp))
             wb2.Activate       
             Set sh2 = wb2.Sheets(c.Value)
             Set fn = sh2.Rows(24).Find(sh1.Range("B5").Value, , xlValues, xlWhole)
             If Not fn Is Nothing Then
                    fn.Offset(1) = sh1.Range("E5").Value
             End If
         Next
    End Sub
    

    附带说明:您的 ppsTest 文件中的工作表未对齐(NPS -tal 在示例 1 中位于不同的行中)。

    【讨论】:

    • 仍然得到同样的错误,可能是别的什么让它给了我这个错误?并感谢示例 1 中错误行的通知。当处于调试模式并运行代码时,我可以将鼠标悬停在 c.value = empty 上,如果这有帮助的话..
    猜你喜欢
    • 2014-12-09
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 1970-01-01
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多