问题
I'm trying to get a small macro to work. Basically, all I want to change is making it paste only values.
I did not write most of this code, only a few snippets. And it goes like this:
Private Sub CommandButton1_Click()
Dim LRSrc As Long, LRDest As Long, SrcRng As Range
With Sheets("Input sheet")
LRSrc = .Cells(.Rows.Count, 1).End(xlUp).Row 'assumes column 1 is contiguous
Set SrcRng = .Range("A2:G" & LRSrc)
End With
If WorksheetFunction.CountA(Range("A2:G2")) = 0 Then
Dim emptyErr As Integer
emptyErr = MsgBox("Data missing or incomplete! Please type in all the fields, starting from row 2", vbOKOnly, "No data")
Else
With Sheets("General inventory")
LRDest = .Cells(.Rows.Count, 2).End(xlUp).Row
SrcRng.Copy .Cells(LRDest + 1, 2)
End With
Dim answer As Integer
answer = MsgBox("Data sent to inventory! Do you wish to clear the sheet?", vbYesNo + vbQuestion, "Empty Sheet")
If answer = vbYes Then
SrcRng.ClearContents
End If
End If
End Sub
I tried to solve it making these changes:
With Sheets("General inventory")
LRDest = .Cells(.Rows.Count, 2).End(xlUp).Row
SrcRng.Copy .Cells(LRDest + 1, 2).PasteSpecial(xlPasteValues)
End With
Dim answer As Integer
answer = MsgBox("Data sent to inventory! Do you wish to clear the sheet?", vbYesNo + vbQuestion, "Empty Sheet")
If answer = vbYes Then
SrcRng.ClearContents
But it gives me the error
Runtime error '1004':
Unable to get the paste special property of the Range class
I have no idea of how to fix it, or whether I should be using PasteSpecial at all.
I appreciate the time you may have taken to read this, and thank you for any advice you may give.
Cheers,
David.-
回答1:
since you're interested in pasting values only, a one liner would be:
.Cells(LRDest + 1, 2).Resize(SrcRng.Rows.Count, SrcRng.Columns.Count).Value = SrcRng.Value
and to shorten the whole thing down a little bit more:
With Sheets("General inventory")
.Cells(.Rows.Count, 2).End(xlUp).Offset(1).Resize(SrcRng.Rows.Count, SrcRng.Columns.Count).Value = SrcRng.Value
End With
回答2:
I don't think you can paste values with 1 line in VBA, so you'll need to split that into two lines:
SrcRng.Copy
.Cells(LRDest + 1, 2).PasteSpecial (xlPasteValues)
来源:https://stackoverflow.com/questions/58421808/pasting-values-only-using-vba-error-unable-to-get-the-pastespecial-property-of