通过VBA

时间:2015-11-03 16:38:31

标签: excel vba excel-vba

我有一个命名范围,我需要根据命名范围中的值来调整大小。例如,如果有十个项目,范围应该是$ A $ 1:$ I11,但我需要缩小和扩展。以下是我到目前为止的情况:

Sub Generate()

Dim wsFail as Worksheet
Dim NextRow As Long, TotalRows As Long

Set wsFail = Sheets("Failure Report")

 wsFail.Activate
    NextRow = Sheets("Failure Report").Range("A" & Rows.Count).End(xlUp).Row
    TotalRows = Range("FailReportTable").Rows.Count
    Sheets("Failure Report").Range("A" & TotalRows).Resize(TotalRows, 9).Value & _
    = Range("FailReportTable").Columns("A:I").Value

End Sub

更新的代码(仍无效)

With wsFail
    .Activate
        NextRow = .Cells(.Rows.Count, .Range("FailReportTable").Cells(1, 1).Column).End(xlUp).Row
        FirstCell = .Range("FailReportTable").Cells(1, 1).Address(False, False)
        LastCol = Split(.Range("FailReportTable").Cells(1, Range("FailReportTable").Columns.Count).Address(True, False), "$")(0)
        NewRange = FirstCell & ":" & LastCol & NextRow
        .ListObjects("FailReportTable").Resize Range("NewRange")
End With

2 个答案:

答案 0 :(得分:1)

调整命名范围(带或不带标题)的最终版本

  1. FailReportTable更改为您的NamedRange名称
  2. Failure Report更改为NamedRange的工作表名称
  3. 代码:

    Sub test_Gerasimos_Zap()
    
    Dim wsFail As Worksheet, _
        FirstCell As String, _
        LastCol As String, _
        NextRow As Long, _
        NewRange As String
    
    Set wsFail = Sheets("Failure Report")
    With wsFail
        .Activate
            NextRow = .Cells(.Range("FailReportTable").Cells(1, 1).Row, .Range("FailReportTable").Cells(1, 1).Column).End(xlDown).Row
            FirstCell = .Range("FailReportTable").Cells(1, 1).Offset(-1, 0).Address(False, False)
            LastCol = Split(.Range("FailReportTable").Cells(1, .Range("FailReportTable").Columns.Count).Address(True, False), "$")(0)
            NewRange = FirstCell & ":" & LastCol & NextRow
        .ListObjects("FailReportTable").Resize Range(NewRange)
    End With
    
    End Sub
    

答案 1 :(得分:1)

这是你想要的吗?此处MyRange仅定义为$B$5$:$B$5$,代码会将其扩展为所有已占用的单元格$B$5:$E$11

scr

Public Sub Test()

    Dim N As Long, M As Long, r As Range

    Set r = Worksheets("Sheet1").Range("MyRange")
    N = CountRows(r)
    M = CountCols(r)

    Debug.Print r.Resize(N, M).AddressLocal
    ' $B$5:$E$11

End Sub

Public Function CountCols(ByVal r As Range) As Long
    If IsEmpty(r) Then
        CountCols = 0
    ElseIf IsEmpty(r.Offset(0, 1)) Then
        CountCols = 1
    Else
        CountCols = r.Worksheet.Range(r, r.End(xlToRight)).Columns.Count
    End If
End Function

Public Function CountRows(ByVal r As Range) As Long
    If IsEmpty(r) Then
        CountRows = 0
    ElseIf IsEmpty(r.Offset(1, 0)) Then
        CountRows = 1
    Else
        CountRows = r.Worksheet.Range(r, r.End(xlDown)).Rows.Count
    End If
End Function