VBA/宏代码获取文本框的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36074350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
VBA/Macro code to get the value of textbox
提问by markerbean
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.valueand randCount = TextBox1.Textbut does not seem to work. What am i missing? How do i get it work. thanks in advance
这是我的代码。我的问题是,如果我更改代码,我只能更改我想要的数据数量randCount = 5。我希望能够使用我的 TextBox 并使用它来定义要获取多少数据。我试过了randCound = TextBox1.value,randCount = TextBox1.Text但似乎不起作用。我错过了什么?我如何让它工作。提前致谢
回答by ThunderFrame
If TextBox1 is on a sheet named Main, then you can use this:
如果 TextBox1 位于名为 Main 的工作表上,则您可以使用以下命令:
Worksheets("Main").TextBox1.Value
Better yet, you can give the sheet a CodeNameof something like shtMainand then use
更好的是,您可以给工作表一个CodeName类似的东西shtMain,然后使用
shtMain.TextBox1.Value
And finally, you can also get to the textbox through the shapes collection (but the methods above are preferable)...
最后,您还可以通过shapes集合进入文本框(但上面的方法更可取)...
Worksheets("Main").Shapes("TextBox1").OLEFormat.Object.Object.Value
回答by TunaLobster
You should be able to use foo = InputBox("bar").
您应该可以使用foo = InputBox("bar").
If however you are getting it from a UserForm then it would be foo = UserForm1.TextBox1.Value
但是,如果您是从 UserForm 获取它,那么它将是 foo = UserForm1.TextBox1.Value

