我有一个带有列标题(在第 1 行)的工作表,每个标题下都有一个 1 到 255 个值的数组。我有为每个标题创建一个新工作表并粘贴值(从第 2 行到第 n 行,每个标题不同)并将工作表重命名为标题标题的代码。假设标题标题是有效的工作表名称。
当我ActiveSheet
是工作表时,下面的代码可以正常Data
工作。
但是,当我使用不同的ActiveSheet
(在同一个工作簿中)运行代码时,我收到此错误:
Run-time error 1004:
Method Range’ of object ‘_Worksheet failed
调试器告诉我错误发生在行上Set src = ws.Range(Cells(2, i), Cells(lastRow, i))
。为什么会出现这个错误?
Sub MakeNewWorksheets()
Dim wb As Workbook
Dim ws As Worksheet
Dim target As Worksheet
Dim i As Long
Dim s As String
Set wb = ThisWorkbook
Set ws = wb.Worksheets("Data")
For i = 1 To ws.UsedRange.Columns.Count
s = ws.Cells(1, i)
If Not SheetExists(s, wb) Then
Set target = wb.Sheets.Add(, wb.Worksheets(wb.Worksheets.Count))
target.Name = s
Else
Set target = wb.Worksheets(s)
End If
' Find data from front sheet
Dim src As Range
Dim lastRow As Long
lastRow = Cells(Rows.Count, i).End(xlUp).Row
Set src = ws.Range(Cells(2, i), Cells(lastRow, i))
'Debug.Print src.Address
' Set values in target sheet
target.Range("A1:A256").Value = src.Value
Next i
End Sub