如果可能,如何在 VBA for Excel 中将任何单元格转换为整数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5499977/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 11:18:34  来源:igfitidea点击:

How can I convert any Cell into an Integer if possible in VBA for Excel?

excelvbaexcel-vbatype-conversion

提问by Lipis

I would like to create a function that will take as a parameter a Celland return an Integer. If the conversion is not successful it should simply return 0, without throwing error messages to the user.

我想创建一个函数,它将作为参数 aCell并返回一个Integer. 如果转换不成功,它应该简单地返回 0,而不向用户抛出错误消息。

I don't care about the cells that contain float values, they could also return 0 since it doesn't look like integer. But text values like 00001234should return 1234and 12 34should return 0.

我不关心包含浮点值的单元格,它们也可以返回 0,因为它看起来不像整数。但是文本值00001234应该返回1234并且12 34应该返回0。

回答by Oneide

How about this:

这个怎么样:

Option Explicit

Public Function ConvertToInteger(Cell As Range) As Integer
   On Error GoTo NOT_AN_INTEGER
   ConvertToInteger = CInt(Cell.Value)
   Exit Function
NOT_AN_INTEGER:
   ConvertToInteger = 0
End Function

Note, for example, that a value of 5.6 will return 6, though. If you want it to be 0 instead, you must check for it and do accordingly.

请注意,例如,值 5.6 将返回 6。如果您希望它为 0,则必须检查它并执行相应的操作。

回答by Andrew Cowenhoven

If the requirement is to return an integral number regardless of length of the input string, you could format your cell to have 0 decimal places and do something like below, which automatically promotes the data type to the precision required. Otherwise you would have to truncate the input value if you really just wanted a VBA integer.

如果要求无论输入字符串的长度如何,都需要返回整数,您可以将单元格的格式设置为 0 位小数并执行如下操作,这会自动将数据类型提升到所需的精度。否则,如果您真的只想要一个 VBA 整数,则必须截断输入值。

Public Function ConvertToIntegral(Cell As Range) As Variant
   On Error GoTo catch
   Dim result As Variant
   result = Val(Cell.Value)
   ConvertToIntegral = result
   Exit Function
catch:
   ConvertToIntegral = 0
End Function