简体   繁体   中英

Excel: For a cell, count the number of words used from a column with words

Goal: search whether words from a column (with a list or words) exist in a cell with a sentence

Explanation : I have two columns, say A contains one sentence per cell. Column B contains a list with one word per cell. For each cell in column A, I want to know whether a word is used from the list in column B.

I would like 2 different outputs:

1) In column C, return the number of words used from column B in the sentence in the cell in column A. Say, in cell C2, return the number of words used from column B in the sentence in cell A2.

For example, if the word list in column B contains:

B2: monkey

B3: donkey

B4: giraffe

B5: elephant

And the sentence in cell A2 says: "the monkey and the elephant are walking" then I would like to return the number "2" in cell C2.

2) In column D until Z? I would like to return the words that are used. So in case of the above example I would like to return in cell:

D2: monkey

E2: elephant

Hopefully somebody can help me out!

This is for the first part:

Try this small UDF() :

Public Function WordCount(r1 As Range, r2 As Range) As Long
   ary = Split(r1.Text, " ")
   bry = r2.Value
   For Each a In ary
      For Each b In bry
         If a = b Then WordCount = WordCount + 1
      Next b
   Next a
End Function

在此处输入图片说明

User Defined Functions (UDFs) are very easy to install and use:

  1. ALT-F11 brings up the VBE window
  2. ALT-I ALT-M opens a fresh module
  3. paste the stuff in and close the VBE window

If you save the workbook, the UDF will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

To remove the UDF:

  1. bring up the VBE window as above
  2. clear the code out
  3. close the VBE window

To use the UDF from Excel:

=myfunction(A1)

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

and for specifics on UDFs, see:

http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx

Macros must be enabled for this to work!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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