尝试运行macros以基于条件突出显示单元格时出现错误1004

我有一个电子表格具有行1中的所有列标题。单元格B2包含一个date。 然后在K2到AH2之后有25个月的列,K1到AH1行的列标题是从当前月份开始的月份。 我试图突出所有从K2到AH2的单元格,只有当它们的列标题date小于B2中的值。

所以比如说B2是13-14-14 K1是获得今天的月份的公式。 所以公式是Today(),格式为MMM-YY (FEB-14)。

我觉得这很容易,因为我只是比较两个date,并突出显示一个不同的单元格,如果一个比另一个小。 我猜我得到一个错误,因为没有将B2date转换为月格式? 这是我收到的错误。

 Run-time error '1004': Application-defined or object-defined error. 

这是我的代码:

 Sub Highlight() Dim firstColumn As Integer Dim lastColumn As Integer Dim firstRow As Integer Dim lastRow As Integer Dim rowCounter As Integer Dim columnCounter As Integer firstColumn = 9 firstRow = 2 lastColumn = 32 lastRow = 6 columnCounter = firstColumn Do Until columnCounter = lastColumn If Cells(K, 1).Value < Cells(B, 2).Value Then Cells(columnCounter, lastRow).Interior.Color = vbYellow End If columnCounter = columnCounter + 1 Loop End Sub 

由于这一行代码,您的错误很可能发生

 If Cells(K, 1).Value < Cells(B, 2).Value Then 

如果你正在使用单元格,那么你需要指定数字行和列(按该顺序),即单元格(1,2)是指第1行第2列或B1。 什么是K和B? 他们是variables,因为他们没有声明或初始化您提供的代码。 因此,它试图find第0行,不存在的单元格。

如果要指定单元格的字母数字位置,请使用Range("K1")Cells(1, "K")

此外,您的代码还有一些其他问题无法完成您想要的function。

  1. 如果Cells(K,1).Value <Cells(B,2).Value Then

即使您修复单元格引用K1和B2,循环的每次迭代都会比较K1和B2。

  1. 单元格(columnCounter,lastRow).Interior.Color = vbYellow

再次,这里的参数必须先行,然后列。 另外,variableslastRow永远不会改变,你已经将它赋值为6,对于循环的每一次迭代它将是6

至less你要做什么,你将需要2个嵌套循环遍历行和列! 我已经写了一些示例代码供您引导。 让我知道如果你需要更多的帮助

 Sub Highlight() Dim firstColumn As Integer Dim lastColumn As Integer Dim firstRow As Integer Dim lastRow As Integer Dim rowCounter As Integer Dim columnCounter As Integer firstColumn = 9 firstRow = 2 lastColumn = 32 lastRow = 6 For columnCounter = firstColumn To lastColumn For rowCounter = firstRow To lastRow If Cells(1, columnCounter) < Cells(rowCounter, "B") Then Cells(rowCounter, columnCounter).Interior.Color = vbYellow End If Next rowCounter Next columnCounter End Sub