在 VBA 中更改单元格数据类型?

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

Change Cell Data Type within VBA?

excelvbamath

提问by loucidity

I am writing an application in excel that helps you to learn the Completing the Square process. I want the cell to be formatted as Number if the variable is an integer, and formatted as a fraction if not.

我正在用 excel 编写一个应用程序,它可以帮助您学习完成 Square 过程。如果变量是整数,我希望单元格格式为数字,如果不是,则格式为分数。

If h = (Int(h)) Then
Range("D1").Select
Selection.NumberFormat = "Number"
Else
Range("D1").Select
Selection.NumberFormat = "?/?"
End If

This code doesn't work for some reason, giving me the following error:

此代码由于某种原因不起作用,给我以下错误:

Unable to set the NumberFormat property of the Range class

无法设置 Range 类的 NumberFormat 属性

Are there any other ways I can do this?

我还有其他方法可以做到这一点吗?

回答by PowerUser

Try:

尝试:

If h = (Int(h)) Then
Range("D1").Select
Selection.NumberFormat = "0"
Else
Range("D1").Select
Selection.NumberFormat = "# ?/?"
End If

However, if you format an integer as a fraction, it'll still show as an integer (i.e. "1" as a fraction is still "1"). So why not just format it as a fraction regardless?

但是,如果您将整数格式化为分数,它仍然会显示为整数(即​​“1”作为分数仍然是“1”)。那么为什么不把它格式化为一个分数呢?