Excel VBA – 如何select与以前的单元格中的值相对应的范围?

我有一个非常大的数据集,包括在NAS的飞机的开始和停止时间。 我想创build一个macros来在Excel中对这些数据进行可视化表示,如下所示:

(注意:这个图片使用假数据)

正如你所看到的,我已经手动完成了前7行,但是有几个数据文件每行有2500+行,这使得这个过程变得单调乏味。 我试图创build一个macros,但我很困惑如何search并select适当的范围来突出显示。

以下是我到目前为止:

Sub autofill() Dim rng As Range Dim row As Range Dim cell As Range 'set the range of the whole search area Set rng = Range("A2:HJ121") For Each row In rng.Rows Dim callsign As Variant Set callsign = cell("contents", "A" & row) Dim valstart As Variant Set valstart = cell("contents", "E" & row) Dim valstop As Variant Set valstop = cell("contents", "F" & row) 'now select the range beginning from the column whose header matches the 'time in valstart and ends at the time which matches the time in valstop Selection.Merge Selection.Style = "Highlight" Selection.Value = callsign Next row End Sub 

select我需要的行最简单的方法是什么?

我不是专业程序员, 如果我的代码显示草率的技术或违反一些圣洁的编程原则,提前道歉。 :P

谢谢!

这是我为此在VBA去。

 Option Explicit Public Sub fillSchedule() Dim startCol As Long Dim endCol As Long Dim i As Long Dim j As Long Dim ws As Excel.Worksheet Dim entryTime As Single Dim exitTime As Single Dim formatRange As Excel.Range Set ws = ActiveSheet startCol = ws.Range("H:H").Column endCol = ws.Range("HJ:HJ").Column Call clearFormats For i = 2 To ws.Cells(1, 1).End(xlDown).Row entryTime = ws.Cells(i, 5).Value exitTime = ws.Cells(i, 6).Value Set formatRange = Nothing For j = startCol To endCol If (ws.Cells(1, j).Value > exitTime) Then Exit For End If If ((entryTime < ws.Cells(1, j).Value) And (ws.Cells(1, j).Value < exitTime)) Then If (formatRange Is Nothing) Then Set formatRange = ws.Cells(i, j) Else Set formatRange = formatRange.Resize(, formatRange.Columns.Count + 1) End If End If Next j If (Not formatRange Is Nothing) Then Call formatTheRange(formatRange, ws.Cells(i, "A").Value) End If Next i End Sub Private Sub clearFormats() With ActiveSheet.Range("H2:HJ121") .clearFormats .ClearContents End With End Sub Private Sub formatTheRange(ByRef r As Excel.Range, ByRef callsign As String) r.HorizontalAlignment = xlCenter r.Merge r.Value = callsign ' Apply color With r.Interior .Pattern = xlSolid .PatternColorIndex = xlAutomatic .ThemeColor = xlThemeColorLight2 .TintAndShade = 0.799981688894314 .PatternTintAndShade = 0 End With ' Apply borders With r.Borders(xlEdgeLeft) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With r.Borders(xlEdgeTop) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With r.Borders(xlEdgeBottom) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With With r.Borders(xlEdgeRight) .LineStyle = xlContinuous .ColorIndex = 0 .TintAndShade = 0 .Weight = xlThin End With End Sub 

条件格式解决scheme如何?

突出显示从H2到(最后右下angular的单元格)的所有单元格。

使用这个公式:

 =IF(AND((H$1>$E2),(H$1<$F2)),TRUE) 

然后申请填写。 而如果你愿意放弃边界和名称范围内的名称,它会为你工作:)。

此外,您可能想从G2中冻结窗格,以便您可以一直滚动到HJ列,并仍然可以看到Callsign列。

希望这可以帮助