我正在创建一个宏但是我被困在这个剪切粘贴语句中并且从昨天开始就无法继续。
问题是:我正在选择“D2到F2”栏中的所有行并将其粘贴在“A1”处。 这是代码:
document.querySelector('input[type=button]').click();
以下是我的尝试:
代码更改:使用Range("D2:F2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Cut
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
代替简单PasteSpecial
。
Paste
代码更改:将选择调整为3列。
Range("D2:F2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Cut
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Select
'ActiveSheet.Paste ' insted of this using paste special.
ActiveSheet.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Range("D2:F2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Cut
Range("A1").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1, 0).Resize(1, 3).Select
'ActiveSheet.Paste
声明。它忽略了错误消息,但也没有粘贴数据。我正在寻找一种方法来忽略此错误消息并继续粘贴。我们在excel表中手动On Error Resume Next
或copy-paste
时通常会出现此错误,我们可以选择忽略和粘贴数据。同样,有什么方法可以在宏中忽略它吗?
答案 0 :(得分:6)
Avoid Select
at all costs。尝试这样的事情
Sub foo()
Dim rng
Set rng = Range("D2:F" & GetLastRow(4))
rng.Cut
Application.Goto Range("A1").Offset(GetLastRow(1))
ActiveSheet.Paste
End Sub
Function GetLastRow(col As Long)
' modified from:
' https://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-vba
If Application.WorksheetFunction.CountA(Columns(col)) <> 0 Then
GetLastRow = Columns(col).Find(What:="*", _
After:=Cells(Rows.Count, col), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Row
Else
GetLastRow = 1
End If
End Function
答案 1 :(得分:1)
正如其他答案和评论中所述,避免不惜一切代价使用.Select
。它是许多常见错误的根源。下一个解决方案通过使用简单函数找到包含数据的最后一行。
Option Explicit
Function lastrow(rng_str As String)
' Adapted from http://www.rondebruin.nl/win/s9/win005.htm
Dim rng As Range: Set rng = Range(rng_str)
Dim r As Range
lastrow = rng.Column
With ActiveSheet
For Each r In rng.Columns
lastrow = Application.Max(lastrow, .Cells(.Rows.Count, r.Column).End(xlUp).Row)
Next
End With
End Function
Sub test()
Dim source_rng As Range
Dim dest_rng As Range
Dim nr_rows As Long
' Maximum number of rows from D to F
nr_rows = lastrow("D2:F2")
Set source_rng = Range("D2:F" & nr_rows)
Set dest_rng = Range("A1")
source_rng.Cut
dest_rng.Activate
ActiveSheet.Paste
End Sub
HTH;)
答案 2 :(得分:0)
问题是您正在尝试选择一个单元格,该单元格是表格末尾下方的一个单元格。停止后,您有一个偏移量,这样可以降低一个单元格。看看这个:
Option Explicit
Sub test()
Range("D2:F2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Cut
Range("A1").Select
Selection.End(xlDown).Select
Debug.Print ActiveCell.Address
Stop
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
End Sub
并且,如前所述,尽量避免选择。