【问题标题】:VB Macros in excel 2016 for Group by multiple columnsexcel 2016中的VBA宏用于按多列分组
【发布时间】:2023-04-03 04:10:02
【问题描述】:

我有以下输入:

我想编写一个宏,它首先按城市分组,然后按车号分组。在输出中,我想要从 MIN(开始日期)到 Max(结束日期)的列,并且每一行都是唯一的车号。每当汽车被占用时,将其标记为红色,否则标记为绿色。

期望的输出:

我知道逻辑但如何在我不知道的宏中实现。

【问题讨论】:

  • 我不愿意为你写所有的代码(也认为我可能做不到)。但是我会为 City 和 Car 获得两个具有唯一值的数组(看 here),然后从适当的列中获取 Max 和 Min 值,然后扫描数组,对于每个数组值,我将遍历您的表并编写新工作表中的所需结果。

标签: excel macros vba


【解决方案1】:

首先,您为什么将“城市”存储在重复的表中?它似乎与汽车相关联,如果是这样,那么只需将其存储在 car/city/dates 表中,如果它必须在另一个表中,则使用 vlookup。这样可以避免潜在的错误...

在回答您的问题时,这是我设置工作表来测试这一点的方法,您必须调整以下代码以适应您的数据布局:

首先,将表格中的所有单元格格式化为绿色/可用。然后,此宏将更改所有预订的单元格。

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

【讨论】:

  • 成功了,谢谢。当我重新运行宏时,我不想覆盖手动编辑的条目,例如:已预订 --- 已预订(至 9:30 AM)
  • 在这种情况下,在更改值之前,您必须包含一个检查!我已经修改了答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-08-05
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-23
  • 2012-08-07
相关资源
最近更新 更多