简体   繁体   English

使用VBA或Excel公式在Excel单元格中搜索部分字符串

[英]Search for a partial string in the excel cell using VBA or Excel formula

I have an Excel sheet with columns template and template name, I have to fill the template name column with a partial string in template column: 我有一个带有列模板和模板名称的Excel工作表,我必须在模板列中用部分字符串填充模板名称列:

    Template                                 Template Name
    This is String  
    String line contains data
    This is Int 
    Int line contain data    
    int: in the String data
    string: in the int data 
    Int: is empty or no string 

I tried the below formula but its giving different results: 我尝试了以下公式,但给出了不同的结果:

     =IF(ISNUMBER(SEARCH("string",A2)),"string",IF(ISNUMBER(SEARCH("int",A2)),"int",IF(ISNUMBER(SEARCH("int:",A2)),"int",IF(ISNUMBER(SEARCH("string:",A2)),"string"))))

Output given by the formula in B column: B列中的公式给出的输出:

    Template                         Template Name
    This is String                       String
    String line contains data            string
    This is Int                          int
    Int line contain data                int 
    int: in the String data              string    #it must be 'int'
    string: in the int data              int       #it must be 'string'
    Int: is empty or no string           string    #it must be 'int'

Please let me know what has to be changed to get the desired output. 请让我知道必须更改什么才能获得所需的输出。

重新排列搜索顺序:如果首先搜索较长的字符串(带有':'),然后搜索没有':'的字符串,则结果应该正确。

=IF(ISNUMBER(SEARCH("string:",A2)),"string",IF(ISNUMBER(SEARCH("int:",A2)),"int",IF(ISNUMBER(SEARCH("int",A2)),"int",IF(ISNUMBER(SEARCH("string",A2)),"string"))))

edited : to make the code suitable for direct entry in the spreadsheet cell (I previuosly thought of a VBA macro) 编辑 :使代码适合直接在电子表格单元格中输入(我以前认为是VBA宏)

if you want the first occurrence between "string" and "int", then use 如果要在“字符串”和“整数”之间第一次出现,请使用

=IF(IFERROR(SEARCH("int",RC1),10000)>IFERROR(SEARCH("string",RC1),10000),"String", "Int")"

should you handle the case where neither "string" nor "int" are in the string, then just advance a check over the occurrence of either one of them 您应该处理字符串中既不是“字符串”也不是“ int”的情况,那么只需检查其中一个是否出现

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM