我试图分别从工作簿AK
,AL
和AM的三列中获取数据。获取数据后,我将进行3种不同的比较,如下代码所示。
首先,我正在比较AL
列和AM
列中的日期。我正在检查AL
列是否为2018年,而AM
列是否为2018年。如果为true,则它将在列L
中插入称为“例程”的文本。使用代码中的for循环逐个单元地完成此操作。
接下来,检查AM
列是否为2018年,并且AK
列是否使用颜色编码为 Yellow 颜色。如果为true,则将文本插入到名为“新建”的列L
中。
最后,需要检查AM
列是否为2018年,并且AK
列是否未用 Yellow 着色。如果为true,则将在“ L”列中插入称为“主要”的文本
否则,该单元将保持空白,不插入任何数据。
问题:代码运行正常,没有问题或错误。但是我无法获得想要的输出。该代码未在列L
Dim j As Long
Dim lastrow As Long
Dim ws1 As Worksheet
Dim wbk As Workbook
Dim wb As Worksheet
Dim date1 As Date, date2 As Date
Set wbk = Application.Workbooks("MaxiTrak RV Service Report - Blank.xlsm")
Set ws1 = wbk.Worksheets("ML_PSV_SERVICE")
lastrow = ws1.range("AL" & Rows.Count).End(xlUp).Row
For j = 2 To lastrow
date1 = ws1.Cells(j, 38).Value
date2 = ws1.Cells(j, 39).Value
If Year(date1) = Year(Date) - 1 And Year(date2) <> Year(Date) - 1 Then
Cells(j, 12).Value = "Routine"
If Year(date2) = Year(Date) - 1 And Cells(j, 37).Interior.ColorIndex = 6 Then
Cells(j, 12).Value = "New"
If Year(date2) = Year(Date) - 1 And Cells(j, 37).Interior.ColorIndex <> 6 Then
Cells(j, 12).Value = "Major"
Else
Cells(j, 12).Value = ""
End If
End If
End If
Next j
答案 0 :(得分:0)
在您提供的以下代码中,您拥有:
If Year(date2) = Year(Date) - 1 And Cells(j, 37).Interior.ColorIndex = 6 Then
Cells(j, 12).Value = "New"
If Year(date2) = Year(Date) - 1 And Cells(j, 37).Interior.ColorIndex <> 6 Then
Cells(j, 12).Value = "Major"
Else
Cells(j, 12).Value = ""
End If
End If
由于cells(j,37).interior.colorindex = 6
而进入第一个if语句的位置,但是随后检查cells(j,37).interior.colorindex <> 6
的位置。
此处的冲突在于,它将始终设置cells(j,12).value = ""
。您的第一个单元格引用已关闭或您的第二个引用已关闭。另一种可能性是您需要更改colorindex
值之一。
答案 1 :(得分:0)
根据您的描述,我认为您有太多if语句。您还可以在另一个if语句中嵌套一个if语句。
Dim j, lastrow As Long
Dim ws1, wb As Worksheet
Dim wbk As Workbook
Dim dateAL, dateAM As Date
Dim colorID As Variant
Set wbk = Application.Workbooks("MaxiTrak RV Service Report - Blank.xlsm")
Set ws1 = wbk.Worksheets("ML_PSV_SERVICE")
lastrow = ws1.Range("AL" & Rows.Count).End(xlUp).Row
currentyear = Year(Date)
For j = 2 To lastrow
dateAL = Year(ws1.Cells(j, 38).Value) ' column AL
dateAM = Year(ws1.Cells(j, 39).Value) ' column AM
colorID = ws1.Cells(j, 37).Interior.ColorIndex
If dateAL = currentyear - 1 And dateAM <> currentyear - 1 Then
Cells(j, 12).Value = "Routine"
Else
If dateAM = currentyear - 1 And colorID = 6 Then
Cells(j, 12).Value = "New"
Else
Cells(j, 12).Value = "Major"
End If
End If
Next j
尝试使用上面的代码,但请先检查代码。
答案 2 :(得分:0)
请尝试以下代码,这非常简单且不言自明:
Sub Compare()
Dim lastRow As Long, i As Long
lastRow = Range("AK" & Rows.Count).End(xlUp).Row
For i = 1 To lastRow
If Year(Range("AM" & i)) <> 2018 Then
If Year(Range("AL" & i)) = 2018 Then Range("L" & i) = "Routine"
' column AM has year equal to 2018
ElseIf Range("AK" & i).Interior.ColorIndex = 6 Then
Range("L" & i) = "New"
Else
Range("L" & i) = "Major"
End If
Next
End Sub