Excel VBA Course
Excel VBA Course - From Beginner to Expert

200+ Video Lessons
50+ Hours of Video
200+ Excel Guides

Become a master of VBA and Macros in Excel and learn how to automate all of your tasks in Excel with this online course. (No VBA experience required.)

View Course

copy columns based on checkboxes on userform

0

Hello

I want  copying   selectded checkboxes   start from  column A   to sheet2 from sheet 1  and  when  select another , then  should  copy to next to adjacent column .

my  way  copy  based on  arranging   as  in sheet1, I  don't  want  it.

what  I  want  when  select  one  of  them  start copying from column A   and  when  select  the  others  should  copy  to next  to adjacent column based who select first

thanks 

Answer
Discuss

Answers

0
Selected Answer

Hi Halk

In the attached file, I've made all the checkbox codes (1 to 5) like this, where only the checkbox number in bold changes:

Private Sub CheckBox1_Click()
With CheckBox1
    If .Value = True Then Call CopyColumn(.Caption)
End With
End Sub

Private Sub CheckBox2_Click()
With CheckBox2
    If .Value = True Then Call CopyColumn(.Caption)
End With
End Sub

They pass the checkbox caption (e.g. "EMPLOYEE") to this new single sub under your UserForm (commented for your understanding):

Private Sub CopyColumn(Capt As String)
Dim Src As Long, LstCol As Long

On Error Resume Next
' see if a heading matches the checkbox (and say if not)
Src = sh1.Rows(1).Find(Capt, LookAt:=xlWhole).Column
If Src = 0 Then
    MsgBox "Column not found"
    Exit Sub
End If
' find last used column on sh2
LstCol = sh2.Cells(1, Columns.Count).End(xlToLeft).Column
'copy selected column from sh1 to sh2
sh1.Columns(Src).Copy sh2.Columns(LstCol + 1)

' remove column A if it was empty
If sh2.Cells(1, 1).Value = "" Then sh2.Columns(1).Delete
'adjust column widths
sh2.UsedRange.Columns.AutoFit

Application.CutCopyMode = False

End Sub

That will add columns to sheet2 when the check is made (but not when it is cleared) and you can do it multiple times and even activate sheet 2 then watch the columns being added as the form is checked

Arguably you could remove the first part ("' ' see if a heading matches..." to "End If") but I added it to ensure that the form matches sheet1 headings and the copy portion works.

I also added a button CB1 captioned "Clear sheet2 and start again" to your form. The code is simply:

Private Sub CB1_Click()
' clear sh2
sh2.UsedRange.Value = ""
sh2.UsedRange.Columns.AutoFit

' clear checkboxes
For n = 1 To 5
    Me.Controls("Checkbox" & n).Value = False
Next n

End Sub

Hope this works well for you

Discuss

Discussion

awesome !
thanks  very  much John ! 
Halk (rep: 30) Oct 10, '22 at 6:31 am
Glad it worked for you and thanks for selecting my Answer, Halk.
John_Ru (rep: 6152) Oct 10, '22 at 6:33 am
Add to Discussion


Answer the Question

You must create an account to use the forum. Create an Account or Login