这是我的方法1。正确的结果应产生第1行和第384列。此方法给出的结果正确,但是使用Activate / Select等方法效率极低。
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
答案 0 :(得分:1)
使用.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
答案 1 :(得分:0)
当我想找到包含该值的最后一行或最后一列时:
Option Explicit
Public Function Row_Last(ws As Worksheet) As Long
On Error Resume Next
Row_Last = _
ws.Cells.Find(What:="*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If Row_Last = 0 Then Row_Last = 1
End Function
Public Function Col_Last(ws As Worksheet) As Long
On Error Resume Next
Col_Last = _
ws.Cells.Find(What:="*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
If Col_Last = 0 Then Col_Last = 1
End Function