VBA XLUP | Как да използвам VBA XLUP в Excel? (с примери)

Excel VBA XLUP

Едно нещо, което трябва да имате предвид, докато пишете VBA код, е това, което правите с обикновения работен лист и можете да репликирате същото нещо и във VBA. Една такава ключова дума в кодирането на VBA е „XLUP“, в тази статия ще ви покажем каква е тази ключова дума в кодирането на VBA и как да я използваме в кодирането.

Как да използвам VBA XLUP в кодирането?

Следват примерите за Excel VBA XLUP.

Можете да изтеглите този шаблон на VBA XLUP Excel тук - VBA XLUP шаблон на Excel

Пример # 1 - Преместване на клетки в изтрита позиция на клетките

Например, погледнете сценария на данните по-долу, където трябва да изтриете тези данни с цветни клетки и повече нагоре данните от долните редове до горните данни.

Един от начините да изтриете това в работния лист е да изберете тези клетки, в които можем просто да изтрием целия ред. Но тук ситуациите са малко сложни, тъй като имам цветни клетки в таблица 1, когато изтриваме целия ред, дори редове от таблица 2 също се изтриват, но не искаме това да се случи, вместо това трябва само да изтрием цветни редове и клетките отдолу трябва да се преместят нагоре позицията на изтритите клетки.

Първо изберете цветните клетки и натиснете Ctrl + Минус символ (-), за да отворите опцията „Изтриване“.

Клавиш за бърз достъп за отваряне на опцията „Изтриване“

В прозореца с опции за изтриване имаме четири опции, можем да изберем действието според нашето изискване. Тъй като трябва да преместим клетките нагоре за позицията на изтритите клетки, изберете „Shift Cell Up“.

Ще имаме непроменени редове от Таблица 2.

Това действие във VBA изисква използването на свойството “XLUP” за извършване на подобен набор от действия във VBA. Сега стигнете до прозореца на редактора на VBA и стартирайте името на макроса си.

Код:

 Sub XLUP_Example () Край Sub 

Първо предоставете клетката RANGE, която да бъде включена в тази операция. В това действие първите клетки, които трябва да бъдат изтрити и се придвижат нагоре, са клетки „A5: B5“.

Код:

 Sub XLUP_Example () Обхват ("A5: B5") Край Sub 

За този диапазон от клетки изберете метода “Delete”.

Код:

 Sub XLUP_Example () Диапазон ("A5: B5"). Изтриване на крайния Sub 

Както можете да видите за метода “Delete”, имаме един незадължителен аргумент като [Shift], за този аргумент трябва да въведем аргумента като “XLUP”.

Код:

 Sub XLUP_Example () Диапазон ("A5: B5"). Изтриване на смяна: = xlUp Край Sub 

Сега можете да стартирате този код ръчно или чрез клавишната комбинация на Excel F5, за да видите резултата.

As you can see in Table 1, we have row number 6 moved up to 5th row and on the other hand Table, 2 row (colored) is unaltered, so by using the “VBA XLUP” option we can do this operation.

Example #2 – Find Last Used Row by using XLUP

Imagine a situation where you are in the A20th cell (look at below image) and your last-used cell is A14.

Now if you want to choose the last used cell (A14). how will you do by using a shortcut key???

We would use Ctrl + Up Arrow key to move to the last used cell from the current position.

Shortcut Key to Move to Last used Cell 

So, from the current cell, Ctrl + Up arrow selected the last used cell. Similarly, in VBA coding we use END (XLUP) to perform the same.

Now come back to VBA coding window.

In this window, we will perform the task of finding the last used row in the worksheet. Create a new subprocedure in the VBA window.

Code:

 Sub XLUP_Example1() End Sub 

To store the last used row number. define the variable as the VBA LONG data type.

Code:

 Sub XLUP_Example1() Dim Last_Row_Number As Long End Sub 

Now for this variable, we will assign the last used row number.

Code:

 Sub XLUP_Example1() Dim Last_Row_Number As Long Last_Row_Number = End Sub 

Now use RANGE object and open this object.

Code:

 Sub XLUP_Example1() Dim Last_Row_Number As Long Last_Row_Number = Range( End Sub 

Now mention the active cell (A20) for RANGE object.

Code:

 Sub XLUP_Example1() Dim Last_Row_Number As Long Range("A14").Select Last_Row_Number = Range("A20") End Sub 

Now open END property for supplied range cell.

Code:

 Sub XLUP_Example1() Dim Last_Row_Number As Long Range("A14").Select Last_Row_Number = Range("A20").End( End Sub 

As you can see above, we have to arrow key options like “xlDown”, “xlToLeft”, “xlToRight”, “xlUp”. Since we are moving up from the A14 cell choose the “VBA XLUP” option.

Code:

 Sub XLUP_Example1() Dim Last_Row_Number As Long Range("A14").Select Last_Row_Number = Range("A20").End(xlUp) End Sub 

After moving up from A14 cell we need to mention what we need to do since we need the last used row number I will use ROW property.

Code:

 Sub XLUP_Example1() Dim Last_Row_Number As Long Range("A14").Select Last_Row_Number = Range("A20").End(xlUp).Row End Sub 

Now for the message box assign the value of variable “Last_Row_Number”.

Code:

 Sub XLUP_Example1()  Dim Last_Row_Number As Long Range("A14").Select Last_Row_Number = Range("A20").End(xlUp).Row MsgBox Last_Row_Number End Sub 

Now you can run this code manually or through shortcut key F5, to see the result.

So message box showing the last used row number as 14, so our last data used row number is A14 cell.

In this case, since data is very small we started from A20 cell but when the data is large we cannot say which cell to take into consideration first, in such cases we need to employ a different technique.

We need to use CELLS property, below is the example of the same.

Code:

 Sub XLUP_Example2() Dim Last_Row_Number As Long Last_Row_Number = Cells(Rows.Count, 1).End(xlUp).Row MsgBox Last_Row_Number End Sub 

Now you can run this code manually or through shortcut key F5, to see the result.

Instead of a RANGE object, I have used CELLS property. Let me explain this in detail to you.

ROW.COUNT this will count how many rows are there in column 1. What this will do is it will take into consideration of the last cell in the worksheet instead of random cell address, in the above case we have used A14 as the random cell address.

Things to Remember about VBA XLUP

  • XLUP is the word used in VBA code to replicate the action of the “Up Arrow” key in excel.
  • VBA XLUP is used to move from active cells to the above cell or last used cell.
  • XLUP is generally used along with END property in VBA.