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

亡梦爱人 提交于 2020-01-16 19:24:31

问题


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.

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

回答1:


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

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



回答2:


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]

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



回答3:


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 A in the Range(A2:A line.



来源:https://stackoverflow.com/questions/26163314/excel-vba-how-to-clear-a-dynamic-range-from-below-header-to-last-row

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!