VBA 用户表单。文本框作为单元格的数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22841548/
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 Userforms. Textbox as number value to cell
提问by Clouse24
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. 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!
一段时间以来,我一直在寻找解决方案,但一直没有找到。本质上,我让我的文档用户在用户表单中填充字段,然后我的代码将其放入适当的单元格中。这些输入字段之一是数字,但是,无论我如何指示 excel 格式化单元格,它最终仍然是文本,我无法执行任何计算。我确信这可能是一个非常简单的修复,但到目前为止我没有成功找到解决方案。与往常一样,任何帮助表示赞赏!
thanks!
谢谢!
回答by Tmdean
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
并且您正在输出到 cell 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
(convert to Long)、CInt
(convert to Integer)、CDec
(convert to decimal,对货币值有用)。
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 按钮。