Excel VBA - 如何清除动态范围(从标题下方到最后一行)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26163314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 04:44:23  来源:igfitidea点击:

Excel VBA - How to clear a dynamic range (from below header, to last row)

excelvbaexcel-vba

提问by Brian

I have a loan amortization schedule that creates the amortization schedule depending on the periods, how can I clear the range, before running the loan amortization again? For example, if I run it for a 10 year period, then run it for a 5 year period, years 6-10 still show up because they haven't been cleared.

我有一个贷款摊销时间表,它根据期间创建摊销时间表,在再次运行贷款摊销之前,我如何清除范围?例如,如果我运行 10 年,然后运行 ​​5 年,第 6-10 年仍会出现,因为它们尚未清除。

Here is my code:

这是我的代码:

outRow = 3
With Sheets("Loan")
lCol = .Cells(3, .Columns.Count).End(xlToLeft).Column
lrow = .Cells(.Rows.Count, lCol).End(xlUp).Row
End With

Sheets("Loan").Range(Cells(outRow, 5), Cells(Lastrow, lastCol)).ClearContents

回答by mrbungle

Try this, takes the UsedRange of the worksheet offset 1 row down to and clears contents

试试这个,将工作表偏移 1 行的 UsedRange 向下到并清除内容

With Sheets("Loan").UsedRange
        .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearContents
End With

回答by West Ray

If you add "+1" after .Row you will keep the headings in case the file is empty. [if it is empty and the code runs without "+1" it will erase the headings]

如果您在 .Row 之后添加“+1”,您将保留标题以防文件为空。[如果它是空的并且代码在没有“+1”的情况下运行,它将删除标题]

Dim Lastrow As Long
Lastrow = Range("A" & Rows.Count).End(xlUp).Row +1
Range("A2:A" & Lastrow).Clear

回答by DannyBland

Dim Lastrow As Long
Lastrow = Range("A" & Rows.Count).End(xlUp).Row
Range("A2:A" & Lastrow).Clear

The above will work for clearing all cells in column A. If you need it for multiple columns then change the second Ain the Range(A2:Aline.

以上将用于清除 A 列中的所有单元格。如果您需要它用于多列,请更改ARange(A2:A行中的第二个。