简体   繁体   中英

Excel VBA How to copy and paste a section of cells into a newly made sheet

I'm making a budgeter sort of thing that helps people keep track of their money. I currently have a bunch of code that checks the current month and attempts to make a new sheet with the name (MM/YYYY) unless that sheet has already been made, if it has been made then nothing will happen.

Private Sub Worksheet_Change(ByVal Target As Range)
    nowMonth = Month(Now)
    nowYear = Year(Now)
    sheetNameStr = nowMonth & "," & nowYear

    sheetExists = False
    For Each Sheet In Worksheets
        If sheetNameStr = Sheet.Name Then
            sheetExists = True
        End If
    Next Sheet
    If sheetExists = False Then
        Set ws = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
        ws.Name = sheetNameStr
        MsgBox ("New sheet named " & sheetNameStr & "was created")
    End If
    Sheets("Main").Activate

    Worksheets("Main").Range("A5:D300").Copy Worksheets("sheetNameStr").Range("A1")
End Sub

The problem I am having is trying to copy and paste the history of my purchases/income and pasting it into the new sheet. I always get the

Run-time error '9': Subscript out of range

error.

If anyone could help that'd be great thanks!

Your line saying

Worksheets("Main").Range("A5:D300").Copy Worksheets("sheetNameStr").Range("A1")

is referring to a worksheet called "sheetNameStr" , but you really want to refer to a sheet with the name contained in the variable sheetNameStr , ie

Worksheets("Main").Range("A5:D300").Copy Worksheets(sheetNameStr).Range("A1")

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