范围对象上的Excel VBA运行时错误1004

试图计算是否存在一个网格中的东西是否存在于由它是否填充颜色(这就是我的老板想要它的格式)定义的Excel中。 不是真正的VBA专家,并且在这个循环的第二行出现错误。 variables是在这之前定义的,在循环内部还有一些其他的东西,但是我不包括那个来节省空间。 我很确定这个问题在这里是显而易见的。

With ThisWorkbook.Worksheets("Core List") Do While Not .Range(Cells(3, x)).Value = "" 'while current name box isn't empty name1 = .Range(Cells(3, x)).Value 'sets the name in the stat sheet ThisWorkbook.Worksheets(stat).Range(Cells(4, x - 2)) = name1 Loop End With 

如果代码所在的工作表与“核心列表”不同,则只需使用.Cells ,请参阅:

 With ThisWorkbook.Worksheets("Core List") Do While Not .Cells(3, x).Value = "" 'while current name box isn't empty name1 = .Cells(3, x).Value 'sets the name in the stat sheet ThisWorkbook.Worksheets(stat).Cells(4, x - 2).Value = name1 Loop End With 

1 – 如果只需要一个单元格,则不需要将Cells放在Range内。 如果您使用这样的Cells ,它将从您插入此代码的工作表中取出单元格。 但是,如果您使用.Cells ,则从您在With块中声明的工作表中取出。

注意 :如果x为零或更低,则将失败,表中没有第0列。 另外,如果它太大(我相信256),你也会打击表单的限制。