使用列标题且无条件格式的VBA代码

使用列标题且无条件格式的VBA代码,vba,excel,Vba,Excel,在给定的图像中,我有项目名称及其开始和结束日期。我想编写一个VBA代码,如果开始日期和结束日期之间的差值小于等于3个月,则结束日期以绿色突出显示。此外,我希望能够通过使用列标题名来实现这一点,因为列的位置可能会在将来发生变化。因此,我不想使用条件格式,而是希望使用VBA代码来编写基于列标题名称的动态代码。 感谢您的帮助。提前谢谢 下面的例子怎么样(假设3个月意味着90天): Sub-foo() 将ws标注为工作表:设置ws=工作表(“工作表1”) '在上面声明并设置工作表,根据需要更改工作表1

在给定的图像中,我有项目名称及其开始和结束日期。我想编写一个VBA代码,如果开始日期和结束日期之间的差值小于等于3个月,则结束日期以绿色突出显示。此外,我希望能够通过使用列标题名来实现这一点,因为列的位置可能会在将来发生变化。因此,我不想使用条件格式,而是希望使用VBA代码来编写基于列标题名称的动态代码。 感谢您的帮助。提前谢谢


下面的例子怎么样(假设3个月意味着90天):

Sub-foo()
将ws标注为工作表:设置ws=工作表(“工作表1”)
'在上面声明并设置工作表,根据需要更改工作表1
作为范围开始
变暗结束为范围
LastRow=ws.Cells(ws.Rows.Count,“A”).End(xlUp).Row
'从列A获取包含数据的行数
Set FoundStart=ws.Rows(1).Find(What:=“Start”)'查找带有“Start”的标题
Set FoundEnd=ws.Rows(1).Find(What:=“End”)'查找带有“End”的标题
如果Not FoundStart为Nothing,Not FoundEnd为Nothing,则“如果找到两个标头,则
对于i=2到LastRow,循环从第2行到最后一行

如果ws.Cells(i,FoundStart.Column)-ws.Cells(i,FoundEnd.Column),那么到目前为止您尝试了什么?像这样的问题太多了。尝试搜索VBA列标题。
Sub foo()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your Sheet above, change Sheet1 as required
Dim FoundStart As Range
Dim FoundEnd As Range
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the number of rows with data from Column A
            Set FoundStart = ws.Rows(1).Find(What:="Start") 'find the header with "Start"
            Set FoundEnd = ws.Rows(1).Find(What:="End") 'find the header with "End"
            If Not FoundStart Is Nothing And Not FoundEnd Is Nothing Then 'if both headers are found then
                For i = 2 To LastRow 'loop from row 2 to last
                    If ws.Cells(i, FoundStart.Column) - ws.Cells(i, FoundEnd.Column) <= 90 Then ' if the difference between start and end is less or equal to 90 days
                        ws.Cells(i, FoundEnd.Column).Interior.ColorIndex = 4 'highlight End in Green
                    End If
                Next i
            Else
                MsgBox "Headers Not found!", vbInformation
            End If
End Sub
Sub foo2()
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your Sheet above, change Sheet1 as required
Dim FoundStart As Range
Dim FoundEnd As Range
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
'get the number of rows with data from Column A
            Set FoundStart = ws.Rows(1).Find(What:="Start") 'find the header with "Start"
            Set FoundEnd = ws.Rows(1).Find(What:="End") 'find the header with "End"
            If Not FoundStart Is Nothing And Not FoundEnd Is Nothing Then 'if both headers are found then
                For i = 2 To LastRow 'loop from row 2 to last
                    MonthDiff = DateDiff("m", ws.Cells(i, FoundStart.Column), ws.Cells(i, FoundEnd.Column))
                    If MonthDiff <= 3 Then
                        ws.Cells(i, FoundEnd.Column).Interior.ColorIndex = 4 'highlight End in Green
                    End If
                Next i
            Else
                MsgBox "Headers Not found!", vbInformation
            End If
End Sub