我有一个命名范围,我需要根据命名范围中的值来调整大小。例如,如果有十个项目,范围应该是$ 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
答案 0 :(得分:1)
FailReportTable
更改为您的NamedRange名称Failure Report
更改为NamedRange的工作表名称代码:
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
。
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