首页 > 解决方案 > Find LastColumn:尝试了 2 种方法,每种方法都给出不同的列作为最后

问题描述

这是我的方法#1。正确的结果应该产生第 1 行和第 384 列。这种方法给出了正确的结果,但是对于激活/选择等,它的效率非常低。

Workbooks.Open Filename:=sDest, UpdateLinks:=0
Windows(sDestFile).Activate
Sheets(sDestTab).Select

'Find LastColumn
Dim colLast As Integer
With ActiveSheet
    colLast = Cells(rowTop, Columns.Count).End(xlToLeft).Column
End With

然后我创建了方法 #2。这种方法不那么碍眼,但它始终给我第 1 行和第 386 列作为答案(而不是第 384 列)。我一生都无法弄清楚为什么代码的更改会使我的 LastColumn 移动 2。

Workbooks.Open Filename:=sDest, UpdateLinks:=0

'Find Last Column
Dim colLast As Integer
colLast = Workbooks(sDestFile).Worksheets(sDestTab).Cells(rowTop, Columns.Count).End(xlToLeft).Column

标签: excelvba

解决方案


使用.Find. 尝试这个

Dim lastcol As Long

With Workbooks(sDestFile).Worksheets(sDestTab)
    If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
        lastcol = .Cells.Find(What:="*", _
                      After:=.Range("A1"), _
                      Lookat:=xlPart, _
                      LookIn:=xlFormulas, _
                      SearchOrder:=xlByColumns, _
                      SearchDirection:=xlPrevious, _
                      MatchCase:=False).Column
    Else
        lastcol = 1
    End If
End With

MsgBox lastcol

如果你想在第 1 行找到最后一列,那么试试这个

Dim wb As Workbook
Dim colLast As Long

Set wb = Workbooks.Open(Filename:=sDest, UpdateLinks:=0)

With wb.Sheets(sDestTab)
    colLast = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With

推荐阅读