I am currently working on a Excel VBA project in which I have created a button to find and replace the value in the worksheet depending on the user input, where user will provide a new hardware name, a quantity and the sheet name in which the new value needs to be updated. The hardware name is a unique value, so the update of the quantity should happen depending on the hardware name.
The problem I am facing is that, when I try to update the values, the hardware name is getting updated properly but where as while updating the quantity it is not only updating the quantity of that particular hardware name but is updating all the quantity that matches the old quantity.
Here is how the code looks like:
If .ComboBox1.Value <> vbNullString Then
sName = .ComboBox1.Text 'is combobox name
If Len(.OldHW.Value) > 0 And Len(.NewHW.Value) > 0 Then
sOldText = .OldHW.Text 'OldHW and NewHW are textbox names
sNewText = .NewHW.Text
With Worksheets(sName)
.Cells.replace what:=sOldText, Replacement:=sNewText, LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End With
End If
If Len(.Oldqty.Value) > 0 And Len(.Newqty.Value) > 0 Then
qOldText = .Oldqty.Text
qNewText = .Newqty.Text
With Worksheets(sName)
.Cells.replace what:=qOldText, Replacement:=qNewText, LookAt:=xlWhole, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
End With
End If
End If
End With
Please any input will be greatly appreciated…
Thank you.
The problem here is that you are doing two seperate and independant search/replace operations. The result will be exactly what you describe, all matching
qOldTextvalues will be replaced.The correct approach would be when you search for the
sOldTextreturn a reference to the cell it findsThen replace sOldText in the located cell and qOldText in a cell relative to the located cell. The position of the Qty cell must depend on the sheet layout. For example if its in the same row, next column use:
From your question it would seem qOldText has no use, unless there is somthing I’ve missed.