【问题标题】:Guidance required for VBA code to copy data from multiple worksheets to another worksheetVBA 代码将数据从多个工作表复制到另一个工作表所需的指导
【发布时间】:2013-06-04 19:11:22
【问题描述】:

您好,我在下面编写了代码,用于将特定范围的单元格从一个工作表复制到另一个名为 “报告”。

Sub sample()

Dim lastRow As Long
Dim col As Long
Dim a As String, b As String, c As String

With Sheets("Jack")
lastRow = .Range("A" & Rows.Count).End(xlUp).Row

If lastRow < 4 Then lastRow = 4

For i = 5 To lastRow
For col = 2 To 31
If .Cells(i, col) <> "" Then

a = .Cells(1, 2)
b = .Cells(i, 1)
c = .Cells(i, col)
d = .Cells(3, col)

With Sheets("Report")
.Range("A" & .Range("A" & .Rows.Count).End(xlUp).Row + 1).Value = a
.Range("B" & .Range("B" & .Rows.Count).End(xlUp).Row + 1).Value = b
.Range("C" & .Range("C" & .Rows.Count).End(xlUp).Row + 1).Value = c
.Range("D" & .Range("D" & .Rows.Count).End(xlUp).Row + 1).Value = d
End With
End If
Next
Next

End With
End Sub

上面的代码非常适合从名为“Jack”的单个工作表中复制数据,但我也在尝试从其他工作表中获取数据。共有 10 个工作表,我想将数据从 sheet2 复制到 sheet7,并希望跳过 sheet1、sheet 8、9 和 10。 任何帮助创建循环以从选定的工作表中复制数据将不胜感激。 谢谢

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    如果所有数据都相同,那么它应该像替换你的一样简单

    With Sheets("Jack")
    

    For x = 2 To 7
    
    With Sheets(x)
    

    并在最后添加一个 Next。

    所以完整的代码如下所示:

    Sub sample()
    
    
    Dim lastRow As Long
    Dim col As Long
    Dim a As String, b As String, c As String
    
    For x = 2 To 7
    
    With Sheets(x)
    
    lastRow = .Range("A" & Rows.Count).End(xlUp).Row
    
    If lastRow < 4 Then lastRow = 4
    
    For i = 5 To lastRow
    For col = 2 To 31
    If .Cells(i, col) <> "" Then
    
    a = .Cells(1, 2)
    b = .Cells(i, 1)
    c = .Cells(i, col)
    d = .Cells(3, col)
    
    With Sheets("Report")
    .Range("A" & .Range("A" & .Rows.Count).End(xlUp).Row + 1).Value = a
    .Range("B" & .Range("B" & .Rows.Count).End(xlUp).Row + 1).Value = b
    .Range("C" & .Range("C" & .Rows.Count).End(xlUp).Row + 1).Value = c
    .Range("D" & .Range("D" & .Rows.Count).End(xlUp).Row + 1).Value = d
    End With
    End If
    Next
    Next
    
    End With
    Next x
    
    End Sub
    

    【讨论】:

    • 非常感谢,我刚刚申请了,它正在工作。真的非常感谢您的努力和投入,很难找到表达感谢的词。我只有一个问题,是否可以根据“Value = B”的行数合并“Value = a”。希望这两张图片将有助于正确理解问题link 和 [link]((i40.tinypic.com/fxth03.jpg))
    • 您可以使用 .merge 方法:Range(xlcell, xlcell.offset(1, 0)).Merge。您可以通过循环并返回地址(for each xlCell in xlRange | if xlCell.value like valFind then | flg = true |strAddresses = strAddresses + xlcell.address| elseif flg = true then exit for | end if)来构建范围内每个唯一值的列表您可能希望保证搜索是通过降序完成的,您可以使用行偏移量和@987654328 @循环
    猜你喜欢
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-04
    • 2021-06-23
    相关资源
    最近更新 更多