我最近遇到了一个问题,我的 get_lcol
函数返回 A1
作为 A1:D1
中的单元格被合并了。我调整了我的函数来解决这个问题,但后来我有一些其他数据与单元格合并在 A1:D1
中。但 G
中的另一列我的函数返回 D1
所以我再次调整它。问题是我不相信它仍然可以处理所有数据类型,因为它只检查第 1 行中的合并单元格。
看看下面的数据,我怎样才能可靠地让函数返回 D
或 4
无论我将合并的行移动到哪里和/或我没有预见到的任何其他问题?
当前功能:
Public Sub Test_LCol()
Debug.Print Get_lCol(ActiveSheet)
End Sub
Public Function Get_lCol(WS As Worksheet) As Integer
Dim sEmpty As Boolean
On Error Resume Next
sEmpty = IsWorksheetEmpty(Worksheets(WS.Name))
If sEmpty = False Then
Get_lCol = WS.Cells.Find(What:="*", after:=[A1], SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
If IsMerged(Cells(1, Get_lCol)) = True Then
If Get_lCol < Cells(1, Get_lCol).MergeArea.Columns.Count Then
Get_lCol = Cells(1, Get_lCol).MergeArea.Columns.Count
End If
End If
Else
Get_lCol = 1
End If
End Function
更新:试试这个带函数的数据:
最佳答案
这是经典的“查找最后一个单元格”问题的一个转折点
陈述目标:
该方法:
.Count > 0
) 中的数据,如果为 true,则返回 IsNull(.MergeCells)
)笔记
Function MyLastCol(ws As Worksheet) As Long
Dim ur As Range
Dim lastcell As Range
Dim col As Long
Dim urCol As Range
Dim urCell As Range
Set ur = ws.UsedRange
Set lastcell = ws.Cells.Find("*", ws.Cells(1, 1), xlFormulas, , xlByColumns, xlPrevious)
For col = ur.Columns.Count To lastcell.Column - ur.Column + 2 Step -1
Set urCol = ur.Columns(col)
If Application.CountA(urCol) > 0 Then
MyLastCol = urCol.Column
Exit Function
End If
If IsNull(urCol.MergeCells) Then
For Each urCell In urCol.Cells
If urCell.MergeCells Then
If Not IsEmpty(urCell.MergeArea.Cells(1, 1)) Then
MyLastCol = urCol.Column
Exit Function
End If
End If
Next
End If
Next
MyLastCol = lastcell.Column
End Function
关于excel - 在有或没有合并单元格的情况下可靠地获取 Excel 中的最后一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70009244/