使用工作表变量名称查找工作表的最后一列

时间:2019-03-28 11:43:42

标签: excel vba

我正在尝试使用名为工作表的变量来查找该工作表的最后一列。如果我命名工作表,我的公式似乎可以工作,但是当我使用变量名来引用工作表时,我的公式却无效。

Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")

Dim LastCol As Integer

''-------------------------------------------------''

LastCol = ws.Cells(1, ws.Columns.Count).End(xlToLeft).Column
MsgBox LastCol

这应该导致显示第8列,但由于某种原因返回1。如果我将“ ws”替换为工作表的实际名称(如下所示),则它可以正常工作。

LastCol = Worksheets("Sheet1").Cells(1, Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column

我对为什么没有显示相同的结果感到困惑。

1 个答案:

答案 0 :(得分:1)

三种可能的解决方案:

Option Explicit

Sub test()

    Dim LastColumn As Long
    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ThisWorkbook
    Set ws = wb.Worksheets("Sheet1")

    'Method 1
    With ws
        LastColumn = .Cells(7, .Columns.Count).End(xlToLeft).Column '<- Change number save to the row number you want to get the last column
    End With

    'Method 2
    With ThisWorkbook.Worksheets("Sheet1")
        LastColumn = .Cells(7, .Columns.Count).End(xlToLeft).Column
    End With

    'Method 3
    LastColumn = ThisWorkbook.Worksheets("Sheet1").Cells(7, ThisWorkbook.Worksheets("Sheet1").Columns.Count).End(xlToLeft).Column

End Sub