Excel将信元按字母/数字拆分成2个单独的单元格

假设您有两张工作表,第一张工作表中有很多不同的数据。 在D列中,你有一个数字(粗体)。 数字的第一部分是2或3个字母,然后是它后面的几位数字(位数可以变化),例如HTG5342355PO23455 ,不是D列中的每个单元格都有这样的编号,它可以在D3中,可以在D6,D7,D20 …(它总是在D列中)

怎么可能将第一个2或3个字母复制到第二个工作表中作为一个单元格,而将数字作为另一个单元格紧挨着它。

编辑:

只是想为这个问题添加一些信息:

在D列中,还有其他的数据,所以它看起来像这样:

**HTG5342355** another text **PO23455** **BT3452342** something something else **NN23355** 

只有粗体的数字需要拆分,其他的东西与其他工作表不相关

使用Sheet2!D1中的数据,将以下公式放在要返回零件的位置:

对于开头的字母:

 =LEFT(Sheet2!D1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},Sheet2!D1&"0123456789"))-1) 

对于最后的数字:

 =MID(Sheet2!D1,MIN(FIND({0,1,2,3,4,5,6,7,8,9},Sheet2!D1&"0123456789")),99) 
 Dim cellvalue as string, textlength as integer, foundnumber as boolean, _ y as integer, x as integer with thisworkbook.sheet1 do until .cells(y,4).value=vbnullstring cellvalue=.cells(y,4).value textlength=len(cellvalue) if textlength > 1 then foundnumber=false for x= 2 to textlength if foundnumber=false then if isnumber(mid(cellvalue,x,1)) then foundnumber=true thisworkbook.sheet2.cells(y,4).value=left(cellvalue,x-1) thisworkbook.sheet2.cells(y,5).value=mid(cellvalue,x) end if end if next x end if y=y+1 loop end with 

我相信这会起作用,虽然我有点时间没有testing它。 它可能需要一些更多的testing,以确保单元格中的数据是你想要复制的types,但希望它会让你开始。 我稍后可以回来评论。

随着公式(复制到适合):

 =IF(ISNUMBER(VALUE(MID(Sheet1!$D1,3,1))),LEFT(Sheet1!$D1,2),LEFT(Sheet1!$D1,3)) 

 =IF(ISNUMBER(VALUE(MID(Sheet1!$D1,3,1))),MID(Sheet1!$D1,3,LEN($D1)),MID(Sheet1!$D1,4,LEN(D$1))) 

你可以写一个大而复杂的公式,但是,虽然这可能是矫枉过正,但我​​会使用正则expression式。 阅读此问题及其答案以供进一步参考。

VBA支持正则expression式,但您必须在您的项目中启用它们:

  1. 打开VBA编辑器
  2. Tools菜单中,单击References
  3. 查找Microsoft VBScript Regular Expressions 5.5并启用复选标记。

现在,创build一个新的模块并编写一些代码。 像这样的东西:

 function Split_Letters_And_Digits(input_str as String) as String() dim re as RegExp set re = new RegExp dim ans(2) as String with re .global = True .ignoreCase = True .multiline = False .pattern = "([A-Za-z]{2,3})([0-9]*)" ' This pattern will match 2 or 3 upper or lower case letters ' and any number of digits after that. ' Each group is enclosed in parentheses; this will allow you ' to get each group separatedly End With ' Check if the input string matches the pattern if re.test(input_str) then ans(1) = re.replace(input_str, "$1") ans(2) = re.replace(input_str, "$2") ' Those "$1" and "$2" are special tokens that enable you to get ' the first and second piece of the pattern; that's the reason ' for those parentheses in the pattern else ' If the input doesn't match the pattern, exit the function exit function end if Split_Letters_And_Digits = ans end function 

这是一个数组函数。 要使用它,请select一个双单元格区域,并写入=Split_Letters_And_Digits(D3) ,然后按Ctrl + Shift + Enter

您可以编写正则expression式来匹配更复杂的模式(使用普通公式可能无法分割的模式),所以值得学习如何使用它们。

希望这可以帮助你