Merge the same cells in Excel using vbs

Source: Internet
Author: User

Assume there is a table like this

You need to merge the same cells in different rows to achieve the following effect:

 

Follow these steps to use vbs

1. Sort the table first. This column is also the column referenced when the cells are merged, usually the student ID or ID column.

2. press Alt + F11 in the current Excel file to bring up the vbs editor and paste the following code

Sub mergerow ()
'Destare Variables
Dim lrow as double 'last row
Dim srow as double 'current row
Dim cvalue as string 'value used to compare

'The reference column
Dim refcol as integer
Refcol = 2

'The columns You Want To mergen
Dim mercol as integer
Mercol = 2

Application. displayalerts = false
Application. screenupdating = false

With activesheet

'Init the variables
Lrow =. Range ("a1048576"). End (xlup). Row
Srow = lrow
Cvalue =. cells (lrow, refcol). Value

For I = lrow-1 to 1 step-1
Msgbox (. cells (I, refcol). value)
Msgbox (. cells (I, refcol). value = cvalue)
If. cells (I, refcol). value = cvalue then
Else
'Only merge two or more cells
If srow-I> 1 then
For j = 1 to mercol Step 1
. Range (. cells (I + 1, J),. cells (srow, J). Merge
Next
End if

'Reset the variables
Srow = I
Cvalue =. cells (I, refcol). Value
End if
Next

End

Application. displayalerts = true
Application. screenupdating = true
End sub

3. Then press F5 to run

For tables in other formats, you only need to modify the following two parameters:

Refcol is the column referenced during merge. If your student ID column is the third column, you can set this value to 3.

'The reference column
Dim refcol as integer
Refcol =3


Mercol is the number of columns you intend to merge. If your student ID column is followed by a gender column, you can set this value to 3.
'The columns You Want To mergen
Dim mercol as integer
Mercol =3

Merge the same cells in Excel using vbs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.