Reputation: 320
similar questions have been asked but I think I have a different problem:
Workbooks.Open Filename:=filepath & "PLT.xlsx"
Worksheets("Sheet1").Range(Worksheets("Sheet1").Range("A1:B1"), Worksheets("Sheet1").Range("A1:B1").End(xlDown)).Copy
Windows("XXX.xslm").Activate
w1.Range("A4").PasteSpecial Paste:=xlPasteValues
The second line is the problem. In fact, it does not copy the cells I want. When I open that workbook, the whole worksheet is selected.
I do not understand why I get that error.
Upvotes: 0
Views: 247
Reputation: 29244
Yikes. If you want to copy values to it the easy way:
Global fso As New FileSystemObject
Public Sub CopyValuesTest()
' Get references to the files
Dim wb1 As Workbook, wb2 As Workbook
Set wb1 = Workbooks.Open(fso.BuildPath(filepath, "PLT.xlsx"))
Set wb2 = Workbooks("XXX")
' Get references to the sheets
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = wb1.Sheets("Sheet1")
Set ws2 = wb2.Sheets("Sheet1")
' Count non-empty rows under A1. Use 2 columns
Dim N As Integer, M As Integer
N = CountRows(ws1.Range("A1")): M = 2
' This copies the values
ws2.Range("A4").Resize(N, M).Value = ws1.Range("A1").Resize(N, M).Value
End Sub
Public Function CountRows(ByRef r As Range) As Long
If IsEmpty(r) Then
CountRows = 0
ElseIf IsEmpty(r.Offset(1, 0)) Then
CountRows = 1
Else
CountRows = r.Worksheet.Range(r, r.End(xlDown)).Rows.Count
End If
End Function
And make sure your filepath
is defined. Also to use FileSystemObject
see https://stackoverflow.com/a/5798392/380384
Upvotes: 1