【问题标题】:Set VBA Range with Variable End使用可变结束设置 VBA 范围
【发布时间】:2013-11-09 06:17:54
【问题描述】:

我是 VBA 的新手,正在努力理解一些语法。

例如,我有一个从a3:c13 开始的范围,我想将它设置为一个变量,以便稍后将它作为表数组传递给 vlookup。但是,范围是由用户输入根据其大小定义的。它总是从A3 开始,它总是包含A:C 列,但我不知道它会走多远。在这种情况下,我想我会将其设置为:

With range("a3")
    table_array = range(.cells(0,0), .End(xlDown).End(xlToRight)).Select
End With

但是,这似乎不起作用。我收到运行时错误:

Run-time Error '1004': Method '_Default' of object 'Range' failed.

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    假设列 A、B 和 C 的行数相同:

    Sub Macro1()
        Set r = Range("A3")
        Set table_array = Range(r, r.End(xlDown)).Resize(, 3)
    End Sub
    

    【讨论】:

    • 棒极了,快速简洁!
    【解决方案2】:

    您可以在 Col A:C 中找到最后一行,然后构建您的范围?

    Sub Sample()
        Dim ws As Worksheet
        Dim LastRow As Long
        Dim Rng As Range
    
        '~~> Change this to the relevant sheet
        Set ws = ThisWorkbook.Sheets("Sheet1")
    
        With ws
            If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
                LastRow = .Range("A:C").Find(What:="*", _
                              After:=.Range("A1"), _
                              Lookat:=xlPart, _
                              LookIn:=xlFormulas, _
                              SearchOrder:=xlByRows, _
                              SearchDirection:=xlPrevious, _
                              MatchCase:=False).Row
            Else
                LastRow = 1
            End If
    
            If Not LastRow < 3 Then
                Set Rng = .Range("A3:C" & LastRow)
    
                Debug.Print Rng.Address
            Else
                MsgBox "No Data found beyond A3"
            End If
        End With
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多