首页 > 解决方案 > 格式化字符串中的数字而不在 Excel 中提取它们

问题描述

所以这是我的问题:我想格式化在字符串中找到的数字。例如:

输入:'123.64 ABC'

结果:'124 ABC'

或者

输入:'10.23% ABC'

结果:'10% ABC'

我试过谷歌,但似乎所有问题都是关于提取数字,而不是在字符串中格式化它们。我猜 Excel 格式化工具的输入需要数字类型,因此它们不适用于包含字符串的单元格。那么这可能吗?我正在考虑拆分字符串->格式化数字->然后写回字符串。有人可以为此提出解决方案吗?谢谢你。

标签: vbaexcel

解决方案


你可以从这个开始

Sub teste()

 txt = "123.64 ABC"
 pos = InStr(1, txt, " ", vbTextCompare) 'search for space
 num = Left(txt, pos - 1) 'get number until space

'in my case i have to replace a "." by "," to be a number, but you have to test what happens in your case
 num = Replace(num, ".", ",", 1, 1) 

 numR = Round(num) ' round number
 Final = numR & " " & Mid(txt, pos + 1, 500) ' join round number and rest of string

End Sub

祝你好运


推荐阅读