简体   繁体   English

VBA用户表单。 文本框作为单元格的值

[英]VBA Userforms. Textbox as number value to cell

I've been searching for a solution to this for a while and have been unsuccessful in finding. 我一直在寻找解决方案一段时间,但一直没有成功找到。 Essentially, I have the user of my document populating fields in a user form that my code then puts into the appropriate cells. 基本上,我让我的文档的用户在用户表单中填充字段,然后我的代码放入适当的单元格中。 One of these input fields is a number but, no matter how I instruct excel to format the cell, it still is text in the end and I can't perform any calculations. 其中一个输入字段是一个数字但是,无论我如何指示excel格式化单元格,它仍然是文本到底,我无法执行任何计算。 I'm sure this is probably a pretty simple fix but I've been unsuccessful so far in finding a solution. 我相信这可能是一个非常简单的修复,但到目前为止我找不到解决办法。 As always, any help is appreciated! 一如既往,任何帮助表示赞赏!

thanks! 谢谢!

You need to convert the value from text to a numeric type before putting it into a cell. 在将值放入单元格之前,需要将值从文本转换为数字类型。

Assuming your textbox is called txtNumber and you're outputting to cell Output!A1 , the code would be: 假设你的文本框被称为txtNumber并且你输出到单元格Output!A1 ,代码将是:

Sheets("Output").Range("A1") = CDbl(txtNumber)

Other conversion functions you might want to use are CLng (convert to Long), CInt (convert to Integer), CDec (convert to decimal, useful for currency values). 您可能要使用的其他转换函数是CLng (转换为Long), CInt (转换为Integer), CDec (转换为十进制,对货币值有用)。

This code will raise an error if the user types a non-numeric text value into the field. 如果用户在字段中键入非数字文本值,则此代码将引发错误。 You should validate on the textbox's Change event and disable the OK button if invalid data is inputted. 您应该对文本框的Change事件进行验证,如果输入了无效数据,则禁用OK按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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