VB中的macros在Excel 2016中的多列组

我有以下的input:

在这里输入图像说明

我想写一个macros,它将按城市分组,然后是车号。 在输出中,我想要从MIN(开始date)到Max(结束date)的列以及每行作为唯一车号。 每当车辆被占用时,标记为红色,否则为绿色。

期望的输出:

按城市分组,然后车号

我知道逻辑,但如何在macros中实现,我不知道。

首先,你为什么要把“城市”存放在重复的表格中? 它似乎被绑在汽车上,如果是这样的话,只要将它存储在汽车/城市/date表中,并使用vlookup,如果它必须在另一个表中。 这将节省潜在的错误…

回答你的问题,这里是我如何设置工作表来testing这个,你将不得不调整下面的代码来适应你的数据布局:

工作表的屏幕截图

首先,将表格中的所有单元格格式化为绿色/可用。 这个macros然后将改变所有的预订单元格。

Sub bookings() ' This finds the number of rows in the top table (-1 for heading row) Dim numCars As Integer numCars = ActiveSheet.Range("A1").End(xlDown) - 1 ' Tracks the active car row Dim carRow As Integer ' Cells for first row/colum cells in tables Dim dateCell As Range Dim bookingCell As Range ' cycle through the bookings table (bottom) For Each bookingCell In ActiveSheet.Range("A10:" & ActiveSheet.Range("A10").End(xlDown).Address) ' Find which row in top table belongs to this booking's car. Could cause error if doesn't exist! carRow = ActiveSheet.Columns(1).Find(what:=bookingCell.Offset(0, 1).Value, lookat:=xlWhole, LookIn:=xlValues).Row ' Cycle through dates in top table for comparison For Each dateCell In Range("C1:" & ActiveSheet.Range("C1").End(xlToRight).Address) ' Comparison like this will only work on dates stored properly (not as text) ' If this isn't working, convert your dates by multipling them by 1. ' This can be done in a neighbouring cell like =A1*1, then copying values ' See this link for details: ' http://stackoverflow.com/questions/6877027/how-to-convert-and-compare-a-date-string-to-a-date-in-excel ' If the date lies between the booking dates... If dateCell.Value >= bookingCell.Offset(0, 2).Value _ And dateCell.Value <= bookingCell.Offset(0, 3).Value Then With ActiveSheet.Cells(carRow, dateCell.Column) ' Do a check that no manual change has happened if .value = "Available" then ' Change the text to booked and colour to red .Value = "Booked" .Interior.Color = RGB(200, 0, 0) end if End With End If Next dateCell Next bookingCell End Sub