简体   繁体   中英

Range runtime error in Excel VBA

I believe I have everything else figured out but the line Set newSheetName = sht.Range("A1:A") is not pulling any information. I am getting the Run-time error '1004': Method 'Range' of object'_Worksheet' failed. What am I missing?

What I am trying to achieve is for this macro to look at the range in sheet "ARK_E_TEXAS" which is A1 through C23("ARK_E_TEXAS_LIST"). If A1:A has data it will create a new sheet and name that new sheet with the cell name. I am using the Lastrow line to know how many lines to go down and the if function to skip over the blanks.

Sub Create_ARK_E_TEXAS()
    Dim sht As Worksheet
    Dim newSheetName As Range
    Dim dataRange As Range
    Dim Lastrow As Long

    Set sht = ThisWorkbook.Sheets("ARK_E_TEXAS")
    Set newSheetName = sht.Range("A1:A")
    Lastrow = sht.Range("ARK_E_TEXAS_LIST").Rows.Count
    Set dataRange = sht.Range("A1:C" & Lastrow)

For Each newSheetName In dataRange
    If newSheetName.Value <> "" Then
        Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
        Sheets(Sheets.Count).Name = newSheetName.Value ' renames the new worksheet
    End If
Next newSheetName
End Sub

Ok I got my answer with the help of @AlexWeber.

Sub Create_ARK_E_TEXAS()


Dim sht As Worksheet
Dim newSheetName As Range
Dim dataRange As Range
Dim Lastrow As Long

Set sht = ThisWorkbook.Sheets("ARK_E_TEXAS")
Lastrow = sht.Range("ARK_E_TEXAS_LIST").Rows.Count
Set newSheetName = sht.Range("A1:A" & Lastrow)
Set dataRange = sht.Range("A1:A" & Lastrow)

For Each newSheetName In dataRange
If newSheetName.Value <> "" Then
    Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
    Sheets(Sheets.Count).Name = newSheetName.Value ' renames the new worksheet
End If
Next newSheetName
End Sub

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