如何在特殊情况下replaceexcel中的字符
所以我有一个71563 x 3数据集,其中包含化学分子式的列表。 这种化学式的一个例子是C 40 H 56 O 4,其中字母代表化学物质,数字代表其多样性。 我想要做的是用字母'O'replace所有字符'O',但只有当'O'在两个数字之间时,而不是在前面有一个字符。 举个例子:
C57H85N9O9将变成C57H85N9o9,但是C6H13NO2将保持不变。 如果可能的话,我怎样才能在excel中写出这个公式呢?
谢谢
我应该早些时候表示道歉,有些情况下,在字母“O”之前有一个数字,但是它之后没有任何数字。 例如: – C8H16O,应该是C8H16o
好吧,所以我的解决scheme可能不是最紧凑的,但它使用公式工作。 您将不得不适应三列,但是如果您的所有数据都在列A中,这将是如何工作的。
-
将此公式添加到列B.这将忽略单元格中第二个字母开头的O. 它返回单元格中第一个O的位置。
=FIND("O",A1,2)
-
在列B中添加这将给你三个字母的string。
=MID(A1,B1 - 1,3)
-
在C列中,给出了第一个数字。
=LEFT(C1,1)
-
D列检查列C是否是一个整数。
=IF(IFERROR(INT(D1),FALSE),A1,FALSE)
-
E栏进行更换。
=IF(E1 <>FALSE,REPLACE(A1,B1-1,3,LEFT(C1,1) & "o" & RIGHT(C1,1)),A1)
请注意,这假设每个分子只有一个O. 我会尝试更新这个检查多个O的。
编辑:
我把它归结为一个单元格公式。 保持上述虽然解释的步骤。
=IF(IFERROR(INT(MID(A1,FIND("O",A1,2) - 1, 1)), FALSE) <> FALSE, REPLACE(A1,FIND("O",A1,2),1,"o"),A1)
式:
=IF(ISERROR(INT(MID(A1,FIND("O",A1)-1,1))),A1,IF(FIND("O",A1)=LEN(A1),A1,REPLACE(A1,FIND("O",A1),1,"o")))
在标准模块中input以下UDF :
Public Function xlate(s As String) As String Dim N As Long, i As Long, CH As String N = Len(s) xlate = "" If N < 3 Then xlate = s Exit Function End If For i = 2 To N - 1 CH = Mid(s, i, 1) If CH <> "O" Then xlate = xlate & CH Else If IsNumeric(Mid(s, i - 1, 1)) And IsNumeric(Mid(s, i + 1, 1)) Then xlate = xlate & "o" Else xlate = xlate & "O" End If End If Next i xlate = Left(s, 1) & xlate & Right(s, 1) End Function
然后用A1中的数据,在B1中input:
=xlate(A1)
并抄下来
用户定义的函数(UDF)非常易于安装和使用:
- ALT-F11调出VBE窗口
- ALT-I ALT-M打开一个新的模块
- 粘贴东西,closuresVBE窗口
如果保存工作簿,则UDF将随之保存。 如果您在2003年以后使用的是Excel版本,则必须将该文件另存为.xlsm而不是.xlsx
要删除UDF:
- 如上所示调出VBE窗口
- 清除代码
- closuresVBE窗口
从Excel中使用UDF:
= XLATE(A1)
要了解有关macros的更多信息,请参阅:
http://www.mvps.org/dmcritchie/excel/getstarted.htm
和
http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx
有关UDF的具体信息,请参阅:
http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx
macros必须启用这个工作!
编辑#1
这是处理terminalO的更新代码
Public Function xlate(s As String) As String Dim N As Long, i As Long, CH As String N = Len(s) xlate = "" If N < 3 Then xlate = s Exit Function End If For i = 2 To N - 1 CH = Mid(s, i, 1) If CH <> "O" Then xlate = xlate & CH Else If IsNumeric(Mid(s, i - 1, 1)) And IsNumeric(Mid(s, i + 1, 1)) Then xlate = xlate & "o" Else xlate = xlate & "O" End If End If Next i xlate = Left(s, 1) & xlate If Right(s, 1) = "O" And IsNumeric(Right(xlate, 1)) Then xlate = xlate & "o" Else xlate = xlate & Right(s, 1) End If End Function
听起来像一个VBAmacros的工作:
dim rng as range, subrange as range rng = range("A1", "ZZ256") for each subrange in rng rng.value2 = replace(rng.value2, "9O9", "9o9") next rng