简体   繁体   中英

Getting Values from Controls in MS Excel Custom Dialog Boxes

first question here. I've been racking my brains all morning for the simplest thing to do in Excel's VBA: get the value of what a user types into a text box (list box, etc.) in a custom dialog box and copy that, via a macro, into a cell. Not sure why it has to be so ridiculously tough. I've tried the .Value property, the .Text property, everything, but it all comes up blank.

I'd post an image of my dialog box, but I don't have the reputation yet to do so. At any rate, just assume it's a banking dialog box with an Amount text box and two buttons: Ok and Cancel.

And here's my code, cut down to the necessary bit:

Sub AddTransaction()
    frmAddTransaction.Show
    ActiveCell.Offset(0, 1).Range("A1").Select
    ActiveCell.FormulaR1C1 = frmAddTransaction.txtAmount.Value
End Sub

Private Sub cmdCancel_Click()
    Unload frmAddTransaction
End Sub

Private Sub cmdOk_Click()
    Unload frmAddTransaction
End Sub

As I've said, I've tried the .Value and .Text properties and everything else that came to mind. I've tried throwing it up into a MsgBox or just sticking it into a cell and, at this point, I'm racking my brains not only to find the answer but to figure out why Microsoft made is so tough just to take a value from one thing and put it into a cell.

Same thing with the buttons: I'd like to know how to tell a macro what button was pushed. I've tried using any property that even remotely looks promising, as well as adjusting the .Top property so I can compare that number. Everything. Nothing is working.

Any help would be great. I've been stuck on this literally all morning.

You want to add the buttons to the form, not to the sheet. So you have 1 button on the sheet that says "Enter Amount" which runs the following:

Private Sub CommandButton1_Click()
 frmAddTransaction.Show
End Sub

and the user form has 3 elements: an input box (txtAmount) and two buttons.

Private Sub Cancel_Click()
    Me.Unload
End Sub

Private Sub OK_Click()
    'modify this to add it to the correct cell
    ActiveCell.Offset(0, 0).Value = txtAmount.Value
    Me.Unload
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