我正在尝试弄清楚如何在从带有小数的数字字符串中提取的一组数字中,保持小数后面的尾随零。首先,我确定第二个小数的位置,然后使用LEFT函数提取前面的所有内容。理想情况下,我希望提取的数字保持其在字符串中的方式,但有些数字有尾随零,有些则没有(即23.1与23.10不同)。现在,我的代码结果去掉了尾随的零。
编辑:结果不能添加任何其他内容,因为它将在vlookup中使用。
结果应该是什么的示例:
String: 23.10.847475993.38.12039
Result: 23.10
String: 23.1.875934.28301.23814
Result: 23.1下面是我的代码:
Dim Datastring As String
Dim PeriodPosition As Integer
Datastring = Cells(i, 26).Value
PeriodPosition = InStr(1, Datastring, ".", vbTextCompare)
PeriodPosition = InStr(1 + PeriodPosition, Datastring, ".", vbTextCompare)
Cells(i, 27).Value = Left(Datastring, PeriodPosition - 1)如有任何帮助,我们不胜感激!
发布于 2019-11-20 14:37:45
正如@GSerg在评论中指出的那样,OP处理的不是数字,而是标识符。标识符通常最好作为字符串处理。
将其视为一个可以拆分和连接的数组。
Dim DataElements as Variant
Dim SelectedElements as Variant
DataElements = Split(Cells(i, 26).value, ".") '<-- create an array out of the elements
SelectedElements = Array(DataElements(0), DataElements(1)) '<-- create a new array of only the wanted elements
Cells(i, 27).value = "='" & Join(SelectedElements,".")
' The =' at the start will force the entry to be a string, and not automatically interpreted as a number
' Otherwise, you could format the column to be Text rather than General上面的代码将保留原来显示的字符串。
Cells(i,26).value: 23.10.847475993.38.12039
DataElements: 23,10,847475993,38,12039
SelectedElements: 23,10
Cells(i,27).value:='23.10
第二种情况
Cells(i,26).value: 23.1.875934.28301.23814
DataElements: 23,1,875934,28301,23814
SelectedElements: 23,1
单元格(i,27).value:='23.1
发布于 2019-11-21 04:54:15
基于@AJD的答案,我修改了代码,这样就不会有撇号,因为字符串将在vlookup中使用。我不是一个很好的程序员,所以这就是我要处理的公式,但我相信有一种更好更快的方法。
Dim DataElements1 As String
Dim DataElements2 As String
Dim SelectedElements As Variant
DataElements1 = Split(Cells(i, 26).Value, ".")(0)
DataElements2 = Split(Cells(i, 26).Value, ".")(1)
Cells(i, 27).Formula = "=" & DataElements1 & "&"".""&" & DataElements2 & ""
Range("AA3:AA" & RowCount).Copy
Range("AA3:AA" & RowCount).PasteSpecial xlPasteValueshttps://stackoverflow.com/questions/58944867
复制相似问题