Sub CopyRandomRows()
Windows("sample rnd.xlsm").Activate
Rows("1:1").Select
Selection.Copy
Application.CutCopyMode = False
Selection.Copy
Windows("rnd sample draft.xlsm").Activate
Sheets("Random Sample").Select
Rows("1:1").Select
ActiveSheet.Paste
Dim source As Range, target As Range, randCount&, data(), value, r&, rr&, c&
Set source = Workbooks("sample rnd.xlsm").Worksheets("Sheet1").Range("A2:L5215")
Set target = Workbooks("rnd sample draft.xlsm").Worksheets("Random Sample").Range("A2")
randCount = 5
data = source.value
For r = 1 To randCount
rr = 1 + Math.Round(VBA.rnd * (UBound(data) - 1))
For c = 1 To UBound(data, 2)
value = data(r, c)
data(r, c) = data(rr, c)
data(rr, c) = value
Next
Next
target.Resize(randCount, UBound(data, 2)) = data
End Sub
This is my code. My problem is that I can only change the number of data i want if i change the code randCount = 5
. I want to be able to use my TextBox and use it for defining how many data to get. I tried randCound = TextBox1.value
and randCount = TextBox1.Text
but does not seem to work. What am i missing? How do i get it work. thanks in advance
Technically, there are two methods to interact with a cell in VBA: the range method and the cell method. We can use the range method like range(“A2”). The value will give us the value of the A2 cell, or we can use the cell method as cells(2,1). The value will also give us the value of A2 cells.
In the VBA editor go to the View menu and click on Locals Window. Each time F8 is pressed one line of VBA is executed. When the range MyRange is set, you can see that values appear for it in the Locals window. By examining the MyRange object you can drill down to see the values in it.
Example #2 – Setting Value to VBA TextBoxGo to Insert menu > click on UserForm. Step 2: From UserForm Tools, select TextBox and drag it to UserForm. Step 3: Insert a CommandButton under UserForm in the same way you added TextBox. Step 4: Change the caption of the command button to “Submit” under properties.
If TextBox1 is on a sheet named Main, then you can use this:
Worksheets("Main").TextBox1.Value
Better yet, you can give the sheet a CodeName
of something like shtMain
and then use
shtMain.TextBox1.Value
And finally, you can also get to the textbox through the shapes collection (but the methods above are preferable)...
Worksheets("Main").Shapes("TextBox1").OLEFormat.Object.Object.Value
You should be able to use foo = InputBox("bar")
.
If however you are getting it from a UserForm then it would be foo = UserForm1.TextBox1.Value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With