简体   繁体   中英

VBA Run-time error 1004 whe using .Cells() to copy from one sheet and paste in another

If you could help me solve this problem with my code it would be much appreciated. I am receiving the 1004 error Method 'Range' of object '_Worksheet' failed when I run the final line here but the line above that has been commented out works? LC is 6 as this shows up when I am in breakmode.

Public Sub Get_Table()
Dim LR As Long
Dim LC As Long
Dim TD As Worksheet
Dim HTD As Worksheet

ThisWorkbook.Sheets.Add After:=Sheets(1)
ActiveSheet.Name = "Table"
Set TD = ThisWorkbook.Sheets("Table")
Set HTD = ThisWorkbook.Sheets("Hedge Table Data")
'Find out the dimensions of the data that we have
LR = HTD.Cells(HTD.Rows.Count, "A").End(xlUp).Row
LC = HTD.Cells.SpecialCells(xlCellTypeLastCell).Column



With ThisWorkbook.Worksheets("Table")
    .Range("A1:A2").Select
    Selection.Merge
    ActiveCell.Value = "Candidate Group"
    Selection.Font.Bold = True
    Selection.HorizontalAlignment = xlCenter
    Selection.VerticalAlignment = xlCenter
    
    'Notes: -Could format with the bold stuff etc. At the end
    
    For I = 2 To LR
        .Cells(I + 1, 1).Value = I - 2
    Next I
    'We have the number of rows filled
    'Now we look at the columns to set up the table.
    .Range(Cells(1, 2), Cells(1, LC - 1)).Select
    Selection.Merge
    ActiveCell.Value = "Candidate Hedges"
    Selection.Font.Bold = True
    Selection.HorizontalAlignment = xlCenter
    Selection.VerticalAlignment = xlCenter
    For I = 2 To LC - 1
        .Cells(2, I).Value = I - 1
    Next I
    .Range("B3").Select
    ActiveCell.FormulaR1C1 = _
        "=IF('Hedge Table Data'!R[-1]C[1]<>"""",'Hedge Table Data'!R1C[1],"""")"
    Range("B3").Select
    Selection.AutoFill Destination:=Range(Cells(3, 2), Cells(3, LC - 1)), Type:=xlFillDefault
    .Range(Cells(3, 2), Cells(3, LC - 1)).Select
    Selection.AutoFill Destination:=Range(Cells(3, 2), Cells(LR + 1, LC - 1)), Type:=xlFillDefault
    'New VaR column
    .Range(Cells(1, LC), Cells(2, LC)).Select
    Selection.Merge
    ActiveCell.Value = "New VaR"
    Selection.Font.Bold = True
    Selection.HorizontalAlignment = xlCenter
    Selection.VerticalAlignment = xlCenter
    
End With


'This works: HTD.Range(HTD.Cells(2, 1), HTD.Cells(LR, 1)).Copy Destination:=TD.Range("F3")
HTD.Range(HTD.Cells(2, 1), HTD.Cells(LR, 1)).Copy Destination:=TD.Range(Cells(3, 8))


End Sub

I fixed this myself by writing HTD.Range(HTD.Cells(2, 1), HTD.Cells(LR, 1)).Copy Destination:=TD.Cells(3, 8)

There is no range necessary when referring to one cell with.Cells()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM