尝试设置值,而不是复制和粘贴

时间:2018-07-19 18:52:12

标签: vba

我已经能够修改大多数VBA程序,以将范围设置为与其他范围相等,以避免复制和粘贴。它极大地加快了我的代码的速度。但是,在某些情况下,我无法弄清楚如何不使用复制和粘贴。下面是一个示例:

Dim Creation2 As Worksheet
Dim HoleOpener As Worksheet
Dim Dal As Range
Dim Lad As Range
Dim Pal As Range
Dim LastRow As Long
Dim ws As Worksheet
Dim fndList As Variant
Dim rplcList As Variant
Set HoleOpener = Worksheets("HoleOpener")
LastRow = HoleOpener.Range("C" & Rows.Count).End(xlUp).Row

On Error Resume Next
For Each ws In ActiveWorkbook.Worksheets
    If ws.Name <> "Creation2" And ws.Name <> "BitInfoTable" And ws.Name <> "DailyBitInfoTable" And ws.Name <> "BitRunInfoTable" And ws.Name <> "HoleOpener" Then
     Set Lad = ws.Cells.Find(What:="StartCopy", LookIn:= _
    xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=True, SearchFormat:=False).Resize(21, 25).Copy
     Sheets("HoleOpener").Cells(Rows.Count, "A").End(xlUp).Offset(1).PasteSpecial xlPasteValues
    End If
     Next

当我搜索时,找不到没有复制/粘贴的类似操作的任何示例。

2 个答案:

答案 0 :(得分:0)

您只需要将我列出的范围与FoundRangePasteRange中的范围交换,并调整Resize以适合您的需要((21, 25))。您还必须在此处使用.value

这是一个如何将两个范围设置为相等的通用示例。由于您的范围大于一个,因此您需要确保每个范围在行和列上的大小均相等。


Dim FoundRange As Range, PasteRange As Range

Set FoundRange = Range("A1:B10")  'Swap this for your found value ("Lad" in your code)
Set PasteRange = Range("C1").Resize(10, 2)   'Swap this for your destination value

PasteRange.Value = FoundRange.Value

使用与上述代码相同的逻辑以及您的代码,结果将如下所示:

Dim Lad As Range, PasteRange As Range

For Each ws In ActiveWorkbook.Worksheets
    If ws.Name <> "Creation2" And ws.Name <> "BitInfoTable" And ws.Name <> "DailyBitInfoTable" And ws.Name <> "BitRunInfoTable" And ws.Name <> "HoleOpener" Then
        Set Lad = ws.Cells.Find(What:="StartCopy", LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True).Resize(21, 25)
        Set PasteRange = Sheets("HoleOpener").Cells(Rows.Count, "A").End(xlUp).Offset(1).Resize(21, 25)
        Destiation.Value = Lad.Value
    End If
Next ws

答案 1 :(得分:-1)

基本上,您会找到一个符合特定条件的范围,将其复制并粘贴到新范围中。

这是我不使用复制/粘贴即可解决的方法:

  1. 按照您的需要查找范围
  2. 迭代范围内的所有单元格(按列或行)
  3. 将每个单元格的值存储在变量中
  4. 将目标单元格的值设置为步骤3中存储的变量

您可能会猜到,这将需要更多的代码,因此,这实际上是在花费时间编写和维护更多代码或针对性能进行优化之间的折衷方案