我一直在努力弄清楚下面代码中产生错误代码1004的原因。我已经尝试更改范围,以确保代码选择正确的工作表和范围,但收效甚微。
我也尝试评论我知道正在生成错误的代码行 r (Range(Cells(1, i), Cells(lastr, i)).Select)
。
当我对该行代码进行注释时,代码会在没有错误的情况下执行并进入For循环以获得正确的数字或次数,但它无法按照我的预期创建所有9个表。它只会生成第一个表,我使用名称管理器选项卡在它刚创建第一个表的公式下验证了这一点。
With Worksheets("AEC Assignments")
For i = 1 To lastc
With .Columns(i)
lastr = Sheet11.Cells(Rows.Count, i).End(xlUp).Row
With Range(Cells(1, i), Cells(lastr, i))
Range(Cells(1, i), Cells(lastr, i)).Select
Selection.CreateNames Top:=True
End With
End With
Next i
End With
非常感谢任何帮助。我很想知道为什么会这样。仅供参考,我是一个新手,对编码有基本的了解,足以把所有这些放在一起,享受编码的挑战。
非常感谢大家!
'Copy Filtered Data
Dim lrow3 As Long
lrow3 = Sheet10.Cells(Rows.Count, 7).End(xlUp).Row
Sheet10.Range(Sheet10.Cells(1, 7), Sheet10.Cells(lrow3, 7)).Copy
Application.DisplayAlerts = False
'Paste Filtered Data in New Sheet
Dim erow4 As Long
erow4 = Sheet11.Cells(Rows.Count - 1, 1).End(xlUp).Row
Sheet11.Paste Destination:=Worksheets("AEC Assignments").Range(Sheet11.Cells(erow4, 1), Sheet11.Cells(erow4, 1))
Sheets("Teacher Match").Select
Sheet10.Range("A1:G1").Select
Selection.AutoFilter
Application.CutCopyMode = False
Dim lastr As Long
Dim lastc As Long
lastc = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column
With Worksheets("AEC Assignments")
For i = 1 To lastc
With .Columns(i)
lastr = Sheet11.Cells(Rows.Count, i).End(xlUp).Row
With Range(Cells(1, i), Cells(lastr, i))
Range(Cells(1, i), Cells(lastr, i)).Select
Selection.CreateNames Top:=True
End With
End With
Next i
End With
End If
End Sub
最新更新:不再代码错误1004!不幸的是,尚未完成所需的结果。这是更新的代码段:
`Dim wsSrc As Worksheet
Set wsSrc = Worksheets("AEC Assignments")
Dim lastr As Long
Dim lastc As Long
wsSrc.Activate
lastc = wsSrc.Cells(1, Columns.Count).End(xlToLeft).Column
For i = 1 To lastc
lastr = wsSrc.Cells(Rows.Count, i).End(xlUp).Row
Range(Cells(1, i), Cells(lastr, i)).CreateNames Top:=True
Next i`
我对此代码的目的是生成几个命名的单元格范围。目前,我只有1个成功命名它应该生产的9个范围。
答案 0 :(得分:0)
嵌套的Withs有时可能会导致问题,在您的情况下,您甚至不会在问题块中使用With
。另一个问题可能是当您不清楚该工作表是否处于活动状态时,您正在尝试选择范围。
你甚至没有使用With .Columns(i)
所以我会用块来消除它 - 除非这指出了逻辑缺失的错误
如果ActiveSheet不是“AEC Assignments”,那么您需要激活它
替换此代码块
With Worksheets("AEC Assignments")
For i = 1 To lastc
With .Columns(i)
lastr = Sheet11.Cells(Rows.Count, i).End(xlUp).Row
With Range(Cells(1, i), Cells(lastr, i))
Range(Cells(1, i), Cells(lastr, i)).Select
Selection.CreateNames Top:=True
End With
End With
Next i
End With
使用此块
Dim AEC_AssignSht As Worksheet
Set AEC_AssignSht = Sheets("AEC Assignments")
With AEC_AssignSht
For i = 1 To lastc
lastr = Sheet11.Cells(Rows.Count, i).End(xlUp).Row
.Range(Cells(1, i), Cells(lastr, i)).CreateNames Top:=True
Next i
End With