Skip to main content
cancel
Showing results for 
Search instead for 
Did you mean: 

Enhance your career with this limited time 50% discount on Fabric and Power BI exams. Ends September 15. Request your voucher.

Reply
_V_
Helper I
Helper I

Replacing a cells value if value of cell above meets condition

Hey again

 

How do I REPLACE a cells value, if the cell above meets certain conditions?

 

Since the textfilters deletes whole rows, I need the replace funktion.
So what I need is:

_V__0-1754027312593.png

 

 

If a cell is equal "Tara (t)" then replace it with "/" and the content of the cell below with "/"

So I actually wont both of them replaced.

Can you tell me that please?

20 REPLIES 20
v-nmadadi-msft
Community Support
Community Support

Hi @_V_ ,

As we haven’t heard back from you, we wanted to kindly follow up to check if the suggestions  provided by the community members for the issue worked. Please feel free to contact us if you have any further questions.

 

Thanks and regards

And again, another message that does not answer the question.

v-nmadadi-msft
Community Support
Community Support

Hi @_V_ 

May I check if this issue has been resolved? If not, Please feel free to contact us if you have any further questions.


Thank you

more thread pollution

_V_
Helper I
Helper I

Hey guys

 

So somehow I dont get it done with the M Code; I know I have to replace the source and it somehow reminds me in changing sources in html/php making websites, but I always get a error. Maybe because I already have some stuff in the code?

Its basically all the steps I made to get to the last point, where I have to get rid of the Tara + weights related to Tara; after that everything should be clear to extract and use for the diagram

let
    Quelle = Folder.Files("C:\Users\***...***\Desktop\scheine test\06"),
    #"Gefilterte ausgeblendete Dateien1" = Table.SelectRows(Quelle, each [Attributes]?[Hidden]? <> true),
    #"Benutzerdefinierte Funktion aufrufen1" = Table.AddColumn(#"Gefilterte ausgeblendete Dateien1", "Datei transformieren (2)", each #"Datei transformieren (2)"([Content])),
    #"Umbenannte Spalten1" = Table.RenameColumns(#"Benutzerdefinierte Funktion aufrufen1", {"Name", "Source.Name"}),
    #"Andere entfernte Spalten1" = Table.SelectColumns(#"Umbenannte Spalten1", {"Source.Name", "Datei transformieren (2)"}),
    #"Entfernte Fehler1" = Table.RemoveRowsWithErrors(#"Andere entfernte Spalten1", {"Datei transformieren (2)"}),
    #"Erweiterte Tabellenspalte1" = Table.ExpandTableColumn(#"Entfernte Fehler1", "Datei transformieren (2)", Table.ColumnNames(#"Datei transformieren (2)"(#"Beispieldatei (2)"))),
    #"Geänderter Typ" = Table.TransformColumnTypes(#"Erweiterte Tabellenspalte1",{{"Source.Name", type text}, {"Column1", type text}, {"Column2", type text}, {"Column3", type text}, {"Column4", type text}, {"Column5", type text}, {"Column6", type text}, {"Column7", type text}, {"Column8", type text}}),
    #"Höher gestufte Header" = Table.PromoteHeaders(#"Geänderter Typ", [PromoteAllScalars=true]),
    #"Geänderter Typ1" = Table.TransformColumnTypes(#"Höher gestufte Header",{{"ls_0001_0001_20250602_017355_L_070921_00002020_00000002.pdf", type text}, {"Column2", type text}, {"Column3", type text}, {"Spedition", type text}, {"00002008", type text}, {"Column6", type text}, {"Column7", type text}, {"Column8", type text}, {"Column9", type text}}),
    #"Entfernte Spalten" = Table.RemoveColumns(#"Geänderter Typ1",{"00002008"}),
    #"Umbenannte Spalten" = Table.RenameColumns(#"Entfernte Spalten",{{"Column7", "Menge1"}, {"Column8", "Menge2"}, {"Column9", "Menge3"}}),
    #"Entfernte Spalten1" = Table.RemoveColumns(#"Umbenannte Spalten",{"Column6", "Spedition"}),
    #"Hinzugefügte benutzerdefinierte Spalte" = Table.AddColumn(#"Entfernte Spalten1", "Benutzerdefiniert", each [Menge3]),
    #"Entfernte Spalten2" = Table.RemoveColumns(#"Hinzugefügte benutzerdefinierte Spalte",{"Benutzerdefiniert"}),
    #"Ersetzter Wert" = Table.ReplaceValue(#"Entfernte Spalten2",null,"/",Replacer.ReplaceValue,{"Column2", "Column3", "Menge1", "Menge2", "Menge3"}),
    #"Entfernte Spalten3" = Table.RemoveColumns(#"Ersetzter Wert",{"Column3"}),
    #"Gefilterte Zeilen" = Table.SelectRows(#"Entfernte Spalten3", each not Text.StartsWith([Menge2], "(")),
    #"Ersetzter Wert1" = Table.ReplaceValue(#"Gefilterte Zeilen"," t"," Tonnen",Replacer.ReplaceText,{"Menge3"}),
    #"Ersetzter Wert2" = Table.ReplaceValue(#"Ersetzter Wert1"," t"," Tonnen",Replacer.ReplaceText,{"Menge2"}),
    #"Ersetzter Wert3" = Table.ReplaceValue(#"Ersetzter Wert2"," t"," Tonnen",Replacer.ReplaceText,{"Menge1"}),
    #"Ersetzter Wert4" = Table.ReplaceValue(#"Ersetzter Wert3","Pt = preset Tonnenare (Tara-Wert aus dem Speicher)","/",Replacer.ReplaceText,{"Menge2"}),
    #"Ersetzter Wert5" = Table.ReplaceValue(#"Ersetzter Wert4","Pt = preset Tonnenare (Tara-Wert aus dem Speicher)","/",Replacer.ReplaceText,{"Menge1"}),
    #"Ersetzter Wert6" = Table.ReplaceValue(#"Ersetzter Wert5","(Pt)","/",Replacer.ReplaceText,{"Menge1"}),
    #"Ersetzter Wert7" = Table.ReplaceValue(#"Ersetzter Wert6","(Pt)","/",Replacer.ReplaceText,{"Menge2"}),
    #"Ersetzter Wert8" = Table.ReplaceValue(#"Ersetzter Wert7","(Pt)","/",Replacer.ReplaceText,{"Menge3"}),
    #"Ersetzter Wert9" = Table.ReplaceValue(#"Ersetzter Wert8","Lieferart","/",Replacer.ReplaceText,{"Column2"}),
    #"Ersetzter Wert10" = Table.ReplaceValue(#"Ersetzter Wert9","Sorte / AVV","/",Replacer.ReplaceText,{"Column2"}),
    #"Ersetzter Wert11" = Table.ReplaceValue(#"Ersetzter Wert10","Geruch:","/",Replacer.ReplaceText,{"Column2"}),
    #"Ersetzter Wert12" = Table.ReplaceValue(#"Ersetzter Wert11","Nein","/",Replacer.ReplaceText,{"Column2"}),
    #"Gefilterte Zeilen1" = Table.SelectRows(#"Ersetzter Wert12", each not Text.StartsWith([Menge1], "(")),
    #"Ersetzter Wert13" = Table.ReplaceValue(#"Gefilterte Zeilen1","Fa. Zimmermann","/",Replacer.ReplaceText,{"Menge1"}),
    #"Ersetzter Wert14" = Table.ReplaceValue(#"Ersetzter Wert13","Fremdfahrzeug","/",Replacer.ReplaceText,{"Menge1"}),
    #"Entfernte Duplikate" = Table.Distinct(#"Ersetzter Wert14")
in
    #"Entfernte Duplikate"

 

Hi  @_V_ 

Regarding your question on how to replace the source line, you only need to replace the value inside the quotation marks with your own key or token. The rest of the source line, including the syntax around it, should remain unchanged,  just make sure the new value is in quotes.
Try modifying it and check if the issue still persists with the M query.


I hope this information helps. Please do let us know if you have any further queries.
Thank you

v-nmadadi-msft
Community Support
Community Support

Hi @_V_ 

I wanted to check if you had the opportunity to review the information provided. Please feel free to contact us if you have any further questions.


Thank you.

ronrsnfld
Super User
Super User

Here is an example using a shifted column to access both the original cell and the cell below.

Please examine the applied steps to obtain a better idea of the algorithm.

 

let

//Replace Source with your own data source

    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WSlSK1YlWSgKTIYlFiQoaFZpgjqGRMZhOBpMpSApKIApMTOFiYIapGZiqAJOVmOoNQQpiAQ==", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),

//add shifted column
    #"Shifted Column" = 
        Table.FromColumns(
            Table.ToColumns(Source) & 
            {{null} & List.RemoveLastN(Source[Column1],1)},
            type table[Original=text, Shifted=text]),

    #"Replace with /" = Table.ReplaceValue(
        #"Shifted Column",
        each [Original],
        each [Shifted],
        (x,y,z) as text=> if (y="Tara (t)") or (z = "Tara (t)") then "/" else x,
        {"Original"}
    ),
    #"Remove Shifted" = Table.RemoveColumns(#"Replace with /",{"Shifted"})
in
    #"Remove Shifted"

 

Original Data

ronrsnfld_0-1754049147863.png

 

Results

ronrsnfld_1-1754049179624.png

 

 

Repost:


Hi @_V_ ,
Hope you are doing well!

I have created a "Custom Function" to handle the issue. Now you can use this in power query. Find the below M-Code

(
Column_Name as list,
Existing_Value as text,
optional Replacing_Value as text,
optional New_Column_Name as text
)
as table =>

let
CN = Column_Name,
EV = Existing_Value,
RV = Replacing_Value ?? "/",
NCN = New_Column_Name ?? "Data",


List_Creation = List.InsertRange(List.RemoveLastN(CN, 1), 0, {""}),

Table_Creation = Table.FromColumns({CN} & {List_Creation}),

Replacing_Text = Table.FromList(Table.TransformRows(Table_Creation, each if List.Contains(Record.ToList(_), EV) = true then RV else [Column1])),

Output = Table.RenameColumns(Replacing_Text,{{"Column1", NCN}})
in
Output

Balakrishnan_J_0-1754292498261.png

1. Column_Name : You need to select the column for which transformation needs to done.
2. Existing_Value : In your case it is "Tara t".
3. Replacing_Value : In your case it is "/"
4. New_Column_Name: You need to provide new column name.

Note: 3 and 4 is optional.

I have checked the same and its working fine. Find the below M-Code
let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlKK1YGRIYlFiQolYKYxuoApmDQDk+ZKsbEA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Data = _t]),
Output = CF_Text_Replace(Source[Data], "Tara t", "/", "Data")
in
Output

Regards,
Balakrishnan_J

Did I answer your question? If Yes,
Then mark my post as a solution and click on the Thumbs Up 👍 to give Kudos.
Remember: You can mark multiple answers as a solution...


Balakrishnan_J
Frequent Visitor

Hi @_V_

Hope you are doing well !

Here is the another solution for your issue.
Copy and Paste below M-Code in advanced editor of Power Query.

let
Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WMlSK1YlWMgKTIYlFiQolYKYxugAS0wxMmivFxgIA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Data = _t]),

List_Creation = List.InsertRange(List.RemoveLastN(Source[Data], 1), 0, {""}),

Table_Creation = Table.FromColumns({Source[Data]} & {List_Creation}),

Output = Table.FromList(Table.TransformRows(Table_Creation, each if List.Contains(Record.ToList(_), "Tara t") = true then "Tara t" else [Column1]))
in
Output


Regards,
Balakrishnan_J

Did I answer your question? If Yes,
Then mark my post as a solution and click on the Thumbs Up 👍 to give Kudos.
Remember: You can mark multiple answers as a solution...

Hey @Balakrishnan_J 

 

Thanks for your help. Question:

If I use codes like yours with a different source, do I have to replace the whole source line or just the value in the ""? ( "i45WMlSK1YlWMgKTIYlFiQolYKYxugAS0wxMmivFxgIA" )

rohit1991
Super User
Super User

Hi @_V_ 

 

Follow the steps below to solve this problem:

 

Step 1:

  1. Right click on table >> Go to Edit Query

Step 2: Add an Index Column

  1. Select Column (for example Name
  2. Go to Add Column >>  Index Column >>  Select From 0
  3. Select that Index column >>  Go to Add Column Tab  >> click on Standard >> click on subtract >> write 1 >> Ok
  4. Remove Index column and Rename Subtraction column  to Index
  5. Right click on Name column >> make duplicate column of Name column and name it ( for example  PreviousRow)
  6. Select that PreviousRow  column >> Go to Add Column → Index Column → From 0 (name it PreviousIndex

 Step 3: Merge Tables

  1. Click Home >>  Merge Queries >>  Merge Queries as New
  2. Join [Index] with [Previous Index]
  3. Use Left Outer Join

 

rohit1991_0-1754052702882.png

 

Step 4:

  1. Expand the new column → Choose only  Name
  2. Click on Index column and apply sort ascending

STEP 5: Final Add Custom Column

Go to Add Column Tab >> click on Custom Column

Paste this Powerquery

 

Final Output = if Text.Trim([Name]) = "Tara (t)" then "/"
else if Text.Trim([Sample Data_.Name]) = "Tara (t)" then "/"
else [Name]

 

rohit1991_2-1754052702896.png

 

Step 6: Remove extra columns except this

rohit1991_4-1754052879095.png

 

 

 

 


Did it work? ✔ Give a Kudo • Mark as Solution – help others too!
_V_
Helper I
Helper I

Hey @jaineshp my friend, hello @burakkaragoz 

Thanks for the fast input you two

Ill give it a try and let you know

Omid_Motamedise
Super User
Super User

Hi,

It is interesting question but there is no function in power query to check both the rows at the same time, so first add a column including the previous values then use replacing or adding a new column,

 

soe the follwoing code and the new value column is what you want

 

let
    Source = Table.FromRows(Json.Document(Binary.Decompress(Binary.FromText("i45WilCK1YGRIYlFiQoaJZpgTi6mUIpSbCwA", BinaryEncoding.Base64), Compression.Deflate)), let _t = ((type nullable text) meta [Serialized.Text = true]) in type table [Column1 = _t]),
    #"Added Index" = Table.AddIndexColumn(Source, "Index", 0, 1, Int64.Type),
    #"Added Custom" = Table.AddColumn(#"Added Index", "New Value", each if ([Column1]="Tara (t)" or (try Source[Column1]{[Index]-1} otherwise false)="Tara (t)") then "/" else [Column1])
in
    #"Added Custom"

 

If my answer helped solve your issue, please consider marking it as the accepted solution. It helps others in the community find answers faster—and keeps the community growing stronger!
You can also check out my YouTube channel for tutorials, tips, and real-world solutions in Power Query with the following link
https://youtube.com/@omidbi?si=96Bo-ZsSwOx0Z36h
jaineshp
Memorable Member
Memorable Member

Hey @_V_,

Glad to assist again!

I understand you need to handle this data transformation in Power BI. Here are the solutions for replacing "Tara (t)" and the row below it with "/" in Power BI:

Option 1: Power Query M Code (Recommended)

This approach uses Power Query Editor to identify and replace the values:

let
Source = YourTableName,
AddIndex = Table.AddIndexColumn(Source, "Index", 0, 1),
AddHelper = Table.AddColumn(AddIndex, "Helper", each
if [YourColumnName] = "Tara (t)" then "/"
else if [Index] > 0 and Table.SelectRows(AddIndex, each [Index] = [Index] - 1){0}[YourColumnName] = "Tara (t)" then "/"
else [YourColumnName]
),
RemoveColumns = Table.RemoveColumn(AddHelper, {"Index", "YourColumnName"}),
RenameColumn = Table.RenameColumns(RemoveColumns, {{"Helper", "YourColumnName"}})
in
RenameColumn

Steps to implement:

  1. Go to Power Query Editor (Transform Data)
  2. Select your table
  3. Go to Advanced Editor
  4. Replace YourTableName with your actual table name
  5. Replace YourColumnName with your actual column name
  6. Apply the transformation

Option 2: Step-by-Step in Power Query Editor

  1. Add Index Column:
    • Add Column > Index Column > From 0
  2. Add Custom Column:
    • Add Column > Custom Column
    • Name it "ReplacedValues"
    • Formula:

if [YourColumn] = "Tara (t)" then "/"
else if [Index] > 0 and Table.SelectRows(#"Added Index", each [Index] = [Index] - 1){0}[YourColumn] = "Tara (t)" then "/"
else [YourColumn]

  1. Clean up:
    • Remove the original column and index column
    • Rename the new column to match original name

Option 3: DAX Calculated Column (Alternative)

If you prefer using DAX in the data model:

ReplacedColumn =
VAR CurrentRow = [YourColumn]
VAR PreviousRow =
CALCULATE(
MAX([YourColumn]),
FILTER(
YourTable,
[Index] = EARLIER([Index]) - 1
)
)
RETURN
IF(
CurrentRow = "Tara (t)", "/",
IF(PreviousRow = "Tara (t)", "/", CurrentRow)
)

Key Considerations:

  • Power Query (Option 1 & 2) is recommended as it transforms data during load
  • Ensure your table has a proper sort order before applying transformations
  • The M code solution handles the logic automatically
  • Always preview your results before applying changes
  • Consider creating a backup of your original data source

Hello @jaineshp 

 

I tried both option 1 and 2 and dont come far.

The "best" result I got was this:

_V__0-1754285264002.png

 

A lot of errors ^^ I am unsure of what to mark, do I have to replace all english commands, what to replace if for example there is already a "let" command and so on

jaineshp
Memorable Member
Memorable Member

Hey @_V_,

Looking at your screenshot, I can see you're getting syntax errors because you're trying to paste the formula directly into the main M code editor. That's not the right approach - let me give you the correct step-by-step process.

The issue: You're editing the raw M code when you should be using Power Query's GUI interface.

Correct Approach - Use the Interface, Not Raw Code:

  1. First, close the Advanced Editor (where you're currently seeing all those errors)
  2. Add Index Column using the ribbon:
    • In Power Query Editor, go to Add Column tab
    • Click Index ColumnFrom 0
    • This creates a new column called "Index"
  3. Add Custom Column using the ribbon:
    • Still in Add Column tab
    • Click Custom Column
    • In the dialog box:
      • New column name: ReplacedValues
      • Custom column formula:

if [YourColumnName] = "Tara (t)" then "/"
else if [Index] > 0 and Table.SelectRows(#"Added Index", each [Index] = [Index]-1){0}[YourColumnName] = "Tara (t)" then "/"
else [YourColumnName]


Important replacements in the formula:

  • Replace [YourColumnName] with your actual column name (looks like it might be something like [Column1] based on your data)
  • Replace #"Added Index" with the actual step name from your Applied Steps panel

What you should NOT do:

  • Don't paste formulas into the Advanced Editor
  • Don't try to modify the entire M code at once
  • Don't worry about existing "let" statements

What the formula should look like for your data: If your column is called "Column1", the formula would be:

if [Column1] = "Tara (t)" then "/"
else if [Index] > 0 and Table.SelectRows(#"Added Index", each [Index] = [Index]-1){0}[Column1] = "Tara (t)" then "/"
else [Column1]

Try this GUI approach instead of editing the raw M code, and let me know how it goes!

Fixed? ✓ Mark it • Share it • Help others!


Best Regards,
Jainesh Poojara | Power BI Developer

jaineshp
Memorable Member
Memorable Member

Hey @_V_,

Thanks for the feedback!

I see you're running into syntax issues with the M code. This is quite common when working with Power Query - the error messages can be confusing at first. Let me break this down into manageable steps that should work better for your specific case.

From your screenshot, it looks like the M code isn't recognizing your table structure properly. The errors suggest column references and step names aren't matching your actual data.

Option 1: Simple Step-by-Step Approach

  1. In Power Query Editor, first add an Index column:
    • Go to "Add Column" → "Index Column" → "From 0"
  2. Add a Custom Column:
    • Go to "Add Column" → "Custom Column"
    • Column Name: ReplacedValues
    • Formula:

if [YourColumnName] = "Tara (t)" then
"/"
else if [Index] > 0 and
Table.SelectRows(#"Added Index", each [Index] = [Index]-1){0}[YourColumnName] = "Tara (t)" then
"/"
else
[YourColumnName]

 

 

  • Replace YourColumnName with your actual column name (the one containing "Tara (t)")
  • Replace #"Added Index" with the actual step name from your Applied Steps panel

Option 2: Even Simpler Approach

If the above is still complex, try this simpler method:

  1. Add Index Column (as above)
  2. Add Custom Column with this simpler formula:

if [YourColumnName] = "Tara (t)" or
([Index] > 0 and Table.SelectRows(#"Previous Step Name", each [Index] = [Index]-1){0}[YourColumnName] = "Tara (t)")
then "/"
else [YourColumnName]

Key Points to Fix Your Errors:

  1. Don't replace the entire code - just add these as new steps
  2. Use the exact column name from your table (check spelling, spaces, case)
  3. Use the exact step name from your Applied Steps panel (usually something like #"Added Index")
  4. Make sure your table has a proper sort order before starting

Troubleshooting Tips:

  • If you see step names with spaces, they'll be in quotes like #"Added Index"
  • Check your Applied Steps panel on the right to see the exact step names
  • Start with just the Index column first, then add the custom column

 

Fixed? ✓ Mark it • Share it • Help others!


Best Regards,
Jainesh Poojara | Power BI Developer

 

Same result. Of course I check spelling, but somethings off

 

_V__0-1754287614819.png

 

burakkaragoz
Community Champion
Community Champion

Hi @_V_ ,

 

You need to look at the row above and replace based on that. Here's the M code:

Add an index first:

= Table.AddIndexColumn(#"Previous Step", "Index", 0)

Then add custom column:

= Table.AddColumn(#"Added Index", "Updated Column", each 
    let
        currentRow = [Index],
        currentValue = [YourColumn],
        valueAbove = if currentRow > 0 
            then #"Added Index"[YourColumn]{currentRow - 1} 
            else null
    in
        if valueAbove = "Tara (t)" then "/"
        else if currentValue = "Tara (t)" then "/"
        else currentValue
)

Clean up by removing the old column and index.

This checks if the cell above is "Tara (t)" and replaces the current cell with "/". It also replaces "Tara (t)" itself with "/".

The key is using the index to reference the previous row's value. Power Query doesn't naturally look at adjacent rows, so you need the index to make it work.

Make sure to replace "YourColumn" with your actual column name.


If my response resolved your query, kindly mark it as the Accepted Solution to assist others. Additionally, I would be grateful for a 'Kudos' if you found my response helpful.
This response was assisted by AI for translation and formatting purposes.

Helpful resources

Announcements
August Power BI Update Carousel

Power BI Monthly Update - August 2025

Check out the August 2025 Power BI update to learn about new features.

August 2025 community update carousel

Fabric Community Update - August 2025

Find out what's new and trending in the Fabric community.

Top Solution Authors