仅在垂直方向获取当前区域

我想写一个UDF(用户定义函数,又名。macros),将在每个绿色单元格中使用。 在这个函数/macros中想要得到我当前组的绿色单元格旁边框的单元格中最长的string的长度。 为了在macros中这样做,我需要确定一个代表当前单元格旁边的所有框架单元格的范围。 (这个计算应该为一个绿色组中的每个单元格产生相同的范围对象,但是从一个组到另一个不同的单元格。)如何获得这个范围?

在这里输入图像说明

我的第一次尝试是这样的:

Range(Application.Caller.Offset(0, -1).End(xlUp),_ Application.Caller.Offset(0, -1).End(xlDown)) 

但是这个

  • 不起作用
  • 如果呼叫者小区是一个组的最上面或最下面的小区,则会给出错误的范围。

我需要像ActiveCell.Offset(0, -1).CurrentRegion ,但只在垂直方向。

尝试这个:

 Function findlongest() Dim fullcolumn() As Variant Dim lastrow As Long Dim i As Long, j As Long, k As Long Dim tmax As Long tmax = 0 With Application.Caller lastrow = .Parent.Cells(.Parent.Rows.Count, .Column - 1).End(xlUp).Row fullcolumn = .Parent.Range(.Parent.Cells(1, .Column - 1), .Parent.Cells(lastrow, .Column - 1)).Value For j = .Row To 1 Step -1 If fullcolumn(j, 1) = "" Then j = j + 1 Exit For ElseIf j = 1 Then Exit For End If Next j For i = .Row To UBound(fullcolumn, 1) If fullcolumn(i, 1) = "" Then i = i - 1 Exit For ElseIf i = UBound(fullcolumn, 1) Then Exit For End If Next i 'to get the range Dim rng As Range Set rng = .Parent.Range(.Parent.Cells(j, .Column - 1), Parent.Cells(i, .Column - 1)) 'then do what you want with rng 'but since you already have the values in an array use that instead. 'It is quciker to iterate and array than the range. For k = j To i If Len(fullcolumn(k, 1)) > tmax Then tmax = Len(fullcolumn(k, 1)) Next k findlongest = tmax End With End Function 

在这里输入图像说明

你是否在像下面的代码之后:

 Option Explicit Sub GetLeftRange() Dim myRng As Range Set myRng = ActiveCell.Offset(, -1).CurrentRegion Debug.Print myRng.Address End Sub 

注意ActiveCell是您标记为绿色的单元之一。

这是使用Area设置每个范围的示例。

 Sub test() Dim Ws As Worksheet Dim rngDB As Range Dim rngA As Range, rng As Range Set Ws = ActiveSheet With Ws Set rngDB = .Range("a1", .Range("a" & Rows.Count).End(xlUp)) Set rngA = rngDB.SpecialCells(xlCellTypeConstants, xlTextValues) For Each rng In rngA.Areas rng.Offset(, 1).Select '<~~ select is not required but is intended to be visualized Next rng End With End Sub 

在这里输入图像说明