Search cells in excel for string

Question:

So I have a project I’m working on where I have a large excel spreadsheet and I want to search one of the columns/cells and if the cell contains a certain word then I want to add a tag in another column but the same row.

So the cell would have a long description in it and if the description contained a keyword I’m looking for it would add a tag in another column in the same row. I would like to able to search for more than one keyword at a time.

I’ve messed around with openpyxl for awhile but that hasn’t really panned out. I am familiar with python, C, C++, and Java so if you could help me with any of those languages I would really appreciate it. Python is preferred.

Asked By: Lucas

||

Answers:

Say we want to search column A for gold. This macro:

Sub FindGold()
    Dim r As Range
    For Each r In Intersect(ActiveSheet.UsedRange, Range("A:A"))
        If InStr(1, r.Value, "gold") > 0 Then r.Offset(0, 1).Value = "found it"
    Next r
End Sub

can produce:

enter image description here

Adjust the code to meet your schema.

Answered By: Gary's Student
import numpy as np
import pandas as pd

# open excel file
discount = pd.read_excel("C:\data\discount.xlsx", sheet_name="ALL0822")

# search string in cell "Discount Total"
row, col = np.where(discount == "Discount Total")
print(row, col)

# get value from cell
cash = discount.iloc[row,col+2].values[0] 
print(cash)
Answered By: Pornthep Nivatyakul
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.