Excel 从两个长数据类型中选择连续范围

Excel 从两个长数据类型中选择连续范围,excel,vba,Excel,Vba,我试图使用两种长数据类型获得连续范围,但我一直得到错误1004 Private Sub SearchButton_Click() 'Finds the last non-blank cell in a single row or column Dim lRow As Long Dim lCol As Long 'Find the last non-blank cell in column A(1) lRow = Cells(Rows.Count, 1).End(xlUp).R

我试图使用两种长数据类型获得连续范围,但我一直得到错误1004

Private Sub SearchButton_Click()
'Finds the last non-blank cell in a single row or column

Dim lRow As Long
Dim lCol As Long

    'Find the last non-blank cell in column A(1)
    lRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Find the last non-blank cell in row 1
    lCol = Cells(1, "S").Column

    ***Range("rRow", "rCol").Select***

End Sub

VBA不接受倒逗号形式的变量,这些变量用于字符串插入。传递变量时不带逗号。就像下面的代码一样

使用以下命令:

Private Sub SearchButton_Click()
'Finds the last non-blank cell in a single row or column

Dim lRow As Long
Dim lCol As Long

    'Find the last non-blank cell in column A(1)
    lRow = Cells(Rows.Count, 1).End(xlUp).Row

    'Find the last non-blank cell in row 1
    lCol = Cells(1, "S").Column

    Range(Cells(1, 1), Cells(lRow, lCol)).Select
End Sub
你可以试试:

代码:

Option Explicit

Private Sub SearchButton_Click()

    Dim lRow As Long, lCol As Long

    'Refer to you worksheet
    With ThisWorkbook.Worksheets("Sheet1")

        'Find Last row of column A (Based on the example answer is 4)
        lRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        'Find last column of row 5 (Based on the example answer is 7)
        lCol = .Cells(5, .Columns.Count).End(xlToLeft).Column

        'Range select
       .Range(.Cells(1, 1), .Cells(lRow, lCol)).Select

    End With

End Sub
图像:

Option Explicit

Private Sub SearchButton_Click()

    Dim lRow As Long, lCol As Long

    'Refer to you worksheet
    With ThisWorkbook.Worksheets("Sheet1")

        'Find Last row of column A (Based on the example answer is 4)
        lRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        'Find last column of row 5 (Based on the example answer is 7)
        lCol = .Cells(5, .Columns.Count).End(xlToLeft).Column

        'Range select
       .Range(.Cells(1, 1), .Cells(lRow, lCol)).Select

    End With

End Sub

范围(“rRow”、“rCol”)。选择范围的方法不正确。这正是问题所在。我不知道如何从长数据类型中选择连续单元格。我添加了ans。@Jude