A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
Hi Ryydo,
I have been trying to write a few VB codes for click buttons but when I run them I am getting a Run-time error '1004': Select method Range class failed
dialog error box.
Any ideas to why this is occuring?
Private Sub CommandButton2_Click()
'
' year End
'
Sheets("Sheet1").Select
Range("A19").Select (This is the line highlighted during debugging).
Selection.Copy
Range("A5").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
Your problem is due to the fact that you have not qualified the two ranges of interest. In the absence of any qualification, the expressions Range("A19") and Range("A5") are interpreted as applying to the sheet in which the code is found. As your code selects another sheet, it is not possible to select ranges on the original sheet and, as you have discovered, VBA will throw a runtime error.
You could overcome this problem by qualifying the two ranges thus:
'=========>>
Private Sub CommandButton2_Click()
With Sheets("Sheet1")
.Select
.Range("A19").Select
Selection.Copy
.Range("A5").Select
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=False
End With
End Sub
'<<=========
[Note the points which precede the two ranges inside the With - End With structure]
That said, however, it is rarely necessary, efficient or desirable to select range objects. Therefore, I would suggest instead the following adaptation of your code which qualifies the range objects but avoids any selections:
'=========>>
Private Sub CommandButton2_Click()
With Sheets("Sheet1")
.Range("A5") = .Range("A19").Value
End With
End Sub
'<<=========
===
Regards,
Norman