首页 > 解决方案 > Excel VBA 问题 - 复制索引范围的语法

问题描述

嗨 - 我正在尝试将针对特定条件的多张工作表中的数据编译到一张工作表中。我希望它逐步完成从数字 5 到 x 的工作表并执行以下操作 - 查找源工作表范围 E13:E37 中的值为空白的行,并将值从 (RowSource,2) 复制并粘贴到 (RowSource ,5) 到 (RowTarget,2) 到 (RowTarget, 5) 中的目标表 - 将源表单元格“C2”中的值复制并粘贴到每个行目标我的代码有 2 个问题:1. 我得到范围的复制粘贴错误。我尝试了一堆不同的语法,但没有正确。2.实际上并没有遍历所有表格有人可以帮助我吗?谢谢你

Sub Get_Activities()
    Dim c As Range 'count for blank
    Dim j As Integer 'target sheet row
    Dim w As Integer ' sheet number
    Dim Source As Worksheet
    Dim Target As Worksheet
    Dim SheetCount As Integer

    Set Target = ActiveWorkbook.Worksheets("Report") 'where the data is going

    j = 4     ' Start copying to row 4 in target sheet

    w = 5     'start at 5th Worksheet in file which should be the first Plant

    If w <= ActiveWorkbook.Sheets.Count Then

    Set Source = ActiveWorkbook.Worksheets(w) 'where the data is coming from

    For Each c In Source.Range("E13:E37")   ' Look at all the tasks
        If c = "" Then
         Source.Cells(2, 3).Copy Target.Cells(j, 1)
         Source.Range(Cells(c.Row, 2), Cells(c.Row, 5)).Copy
         Target.Range(Cells(j, 2)).PasteSpecial Paste:=xlPasteValues ' Getting an invalid operator error for j.Row

        j = j + 1
        End If

    Next c

  w = w + 1

 End If

End Sub

标签: excelvba

解决方案


问题 1 是由于语法不正确或至少容易出现问题:您应该在两个“单元格”前面添加“源”标识符

Source.Range(Cells(c.Row, 2), Cells(c.Row, 5)).Copy

您还应该摆脱粘贴代码的“范围”,因为它是不需要的,并且也可能导致问题。这两项更改都已在下面的代码块中完成。

 Target.Range(Cells(j, 2)).PasteSpecial Paste:=xlPasteValues

可以在此处找到使用 Range 和 Cells 时需要额外标识符的更好描述 - VBA 复制和粘贴仅在我激活工作表时才有效

问题 2 是您从不遍历工作表,代码在 if 之后结束,对于这种情况,我选择使用“Do While”循环,您可以选择任何您喜欢的循环形式,只要您循环!

Do While w <= ActiveWorkbook.Sheets.Count

Set Source = ActiveWorkbook.Worksheets(w) 'where the data is coming from

For Each c In Source.Range("E13:E37")   ' Look at all the tasks
    If c = "" Then
     Source.Cells(2, 3).Copy Target.Cells(j, 1)
     Source.Range(Source.Cells(c.Row, 2), Source.Cells(c.Row, 5)).Copy
     Target.Cells(j, 2).PasteSpecial Paste:=xlPasteValues ' Getting an invalid operator error for j.Row

    j = j + 1
    End If

Next c

w = w + 1

Loop

推荐阅读