简体   繁体   中英

Swapping Data in excel VBA userform

TL-DR; i need a way to call a variable name. So instead of calling TB_Name1_R1 i can call TB_Name1_R[i] (or whatever its called in VBA)

I am right now working with multiple userforms in excel with VBA.

The setup is as such: I have a main window with a lot of textboxes for input of data by the user. They are all in rows called TB_Name1_R1 , TB_Name2_R1 .. next row is TB_Name1_R2 , TB_Name2_R2 .. and so forth.

A second userform for swapping holds 2 dropdown boxes with lists of the rows, so you can choose lets just say row 1 and 2, and then the idea is that you can swap the data in the two rows. So the userform calls

Private Sub CB1_Click()

Dim Ra As Integer
Dim Rb As Integer

Ra = RowA.ListIndex
Rb = RowB.ListIndex

If Ra = -1 Or Ra = 10 Or Ra = 15 Or Rb = -1 Or Rb = 10 Or Rb = 15 Then
    MsgBox "Wrong input, please redo", , "Wrong Input"
Else
    Call Module1.Move(Ra, Rb)

    Me.Hide
End If

End Sub

All of that works fine.

NOW my problem is as follow. How do i smartest create some code where the called sub use the information sendt to swap the data between the rows chosen?

The only thing i can come up with (and yes it is so very basic) is a hole lot of

if a = 1 then
holder1 = TB_Name1_R1
holder2 = TB_Name2_R1

if a = 2 then
holder1 = TB_Name1_R2
holder2 = TB_Name2_R2

And that simply cannot be the answer

Something similar to the following could replace your last code snippet ...

holder1 = Worksheets("Sheet1").Shapes("TB_R" & a & "_Name1")
holder2 = Worksheets("Sheet1").Shapes("TB_R" & a & "_Name2")

Where, of course, you would need to replace "Sheet1" with the appropriate worksheet name.


Updated based on feedback

This should work, and provide access to the .Text and .Value fields.

Dim holder1 as Control, holder2 as Control
holder1 = UserForm1.Controls("TB_R" & a & "_Name1")
holder2 = UserForm1.Controls("TB_R" & a & "_Name2")

Where UserForm1 is replaced with your Form.

With a mix between OLdUgly's answers and some Internet research, i found the right code to be:

Sub Move(R1, R2)

Dim Name As String
Dim Number As Integer
Dim NN As Variant

Name = "TB_Name_R"
Number = R1

NN = Name & Number

Dim Holder1 As Variant

Holder1 = Main.Controls(NN).Value

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM