使用表格更正语法("")。范​​围

时间:2017-08-07 12:25:53

标签: excel vba excel-vba

我有以下代码可以很好地获取D列中的唯一值并将它们粘贴到工作表中#34; Summary-Champion Specific"。我现在有一些语法问题。而不是创建工作表"摘要 - 冠军特定",我想只选择它(所以它已经创建)。

 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 = "c"
      .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("c")
  .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.我是否以某种方式弄乱了语法?

2 个答案:

答案 0 :(得分:2)

正如Vityata指出的那样,CellsWorksheet.Cells不同,因为Cells指的是ActiveSheet。

但是Sheets命令也会引用ActiveWorkbook,它可能不是你想要的那个。此外,Sheets("SheetName")语法隐式调用_Default的{​​{1}}成员并返回Sheets引用,因此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块中使用该变量:

With

该代码运行速度更快,维护更容易。

答案 1 :(得分:1)

尝试用点来引用细胞。像这样:

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