复制值

问题描述 投票:1回答:2

这里需要一点帮助。

在“数据”选项卡中,我要复制列“ c2:c1000”中的值,并粘贴到另一个选项卡的“ a1”列中。

这是我到目前为止所拥有的,

Dim x As Long
Dim lastRow As Long

lastRow = Worksheet("Data").Cells(3, Columns.Count).End(xlUp).Column

For x = 1 To lastRow
    If Worksheets("Sheet2").Cells(2, "A") = "" Then
        Worksheets("Data").Range("c2:c1000").Copy Destination:=Worksheets("Sheet2").Range(1, "A")

        Sheets("Sheet2").Range("A1").Value = Format(Now, "mm/dd/yyyy HH:mm:ss")

    Else
        Worksheets("Data").Range("c2:c1000").Copy Destination:=Worksheets("Sheet2").Cells(2, 
        Columns.Count).End(xlToLeft).Offset(, 1)
       'Sheets("Sheet2").Range("A1").Value = Format(Now, "mm/dd/yyyy HH:mm:ss") --> can't figure how to increment this as this will need to be on the subsequent empty column 
End If

Next
End Sub

您的帮助将不胜感激!谢谢。

excel vba loops copy-paste
2个回答
0
投票

首先将值粘贴到范围A1中,然后向下粘贴,然后下一次粘贴到单元格B1中,依此类推,将时间戳记留给A1,B1等没有空间。因此,我假设您想将随机值粘贴到第2行。因此,将单元格A1,B1,...留给时间戳。

在With语句中,我们可以引用wsAudit的属性,因此我们可以替换“ Worksheets(” Audit“)。”仅带有“。”的引用

column.count表达式仅检查工作表中的列数。表达式.Cells(2,Columns.Count)只是指向第2行的最后一个单元格。然后,.End(xlToLeft).Column从此列向左看,并且应该找到该行上的最后一个非空单元格。基本上是相同的想法,在Excel的工作表中,您将转到单元格XDF2,然后从键盘上按CTRL +箭头。但是,除了激活单元格外,我们只想获取列索引号,然后添加1(新列)并将其保存到变量中。现在,新列已为人所知。表达式Range(.Cells(2,newColAudit),.Cells(1000,newColAudit))。Value实际上与例如Range(“ B2:B1000”),但与此相反,我们可以使用行索引和列索引号。当列号变化时,这很有用。

而且正如塞缪尔(Samuel)指出的那样,通过将区域设置为相等可以避免复制粘贴操作。

Dim wsAudit As Worksheet
Dim newColAudit As Long

Set wsAudit = Worksheets("Audit")

With wsAudit
    newColAudit = .Cells(2, Columns.Count).End(xlToLeft).Column + 1
    Range(.Cells(2, newColAudit), .Cells(1000, newColAudit)).Value = Worksheets("Data").Range("C2:C1000").Value
    .Cells(1, newColAudit).Value = Format(Now, "mm/dd/yyyy HH:mm:ss")
End With
    

0
投票

非常类似于源工作表的LastRow *变量,为目标工作表创建一个LastColumn变量,它将以与查找最后使用的行相同的方式查找最后使用的列。

© www.soinside.com 2019 - 2024. All rights reserved.