使用表格的正确语法(“”).Range
我有以下代码,在获得D列中的唯一值并将其粘贴到工作表“Summary-Champion Specific”中时可以非常好地工作。 我现在有一些语法问题。 而不是创build工作表“总结 – 冠军具体”,我想只select它(所以它已经创build)。
Dim dict As Object, LastRow As Long, c Set dict = CreateObject("Scripting.dictionary") With Sheets("Raw Data") LastRow = .Cells(.Rows.Count, "D").End(xlUp).Row For Each c In .Range("D8:D" & LastRow).SpecialCells(xlCellTypeVisible) dict(c.Text) = 0 Next End With Champ = dict.keys With Sheets.Add(After:=Sheets(Sheets.Count)) .Name = "Summary-Champion Specific" .Range(Cells(3, 1), Cells(3, 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) .Range(Cells(8 + UBound(Champ), 1), Cells(8 + UBound(Champ), 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) End With
基本上我想把上面的第二部分改为下面的代码。
With Sheets("Summary-Champion Specific") .Range(Cells(3, 1), Cells(3, 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) .Range(Cells(8 + UBound(Champ), 1), Cells(8 + UBound(Champ), 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) End With
当我尝试运行这个,但是,它失败,错误1004.我有不知何故混乱的语法?
尝试用一个点来引用单元格。 喜欢这个:
With Sheets("Summary-Champion Specific") .Range(.Cells(3, 1), .Cells(3, 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) .Range(.Cells(8 + UBound(Champ), 1), .Cells(8 + UBound(Champ), 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) End With
因此,您可以参考正确的工作表。 .Cells
是工作表的一个属性 – https://msdn.microsoft.com/en-us/vba/excel-vba/articles/worksheet-cells-property-excel
正如Vityata所指出的那样, Cells
与Worksheet.Cells
不同,因为Cells
引用了ActiveSheet。
但是Sheets
命令也会引用ActiveWorkbook,这可能不是您想要的。 此外, Sheets("SheetName")
语法隐式地调用Sheets("SheetName")
成员并返回一个Object
引用,所以With
块内的调用都是后期绑定的,因此速度会变慢,得到任何智能感知。
最好在工作簿中使用工作表的(有意义的)代号:
With SummaryChampionSpecific 'Where SummaryChampionSpecific is the CodeName of Sheets("Summary-Champion Specific") .Range(.Cells(3, 1), .Cells(3, 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) .Range(.Cells(8 + UBound(Champ), 1), .Cells(8 + UBound(Champ), 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) End With
或者设置一个Worksheet
variables,然后在With
块中使用它:
Dim mySheet as Worksheet Set mySheet = ThisWorkbooks.Worksheets("Summary-Champion Specific") With mySheet .Range(.Cells(3, 1), .Cells(3, 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) .Range(.Cells(8 + UBound(Champ), 1), .Cells(8 + UBound(Champ), 1)).Resize(dict.Count).Value = Application.Transpose(dict.keys) End With
该代码将运行得更快,更容易维护。