0

I want to write a for loop that takes the value of each cell, passes it into a function called FixID(), then outputs the result of the function into the value of the cell. The below code passes in values to the function fine, but it does not write the new value to the cell.

Sub test()
Total_Rows = Cells(Rows.Count, 3).End(xlUp).Row
For Each C In Range("A3", "C" & Total_Rows )
   C = FixID(C.Value)
Next

End Sub
2
  • What is the output of FixID? Commented May 27, 2014 at 21:47
  • The output is just a string. The input is also a string. Commented May 27, 2014 at 21:49

1 Answer 1

1

UPDATE: Here is a quick little example I put together to test the technique, and it worked as expected...

Option Explicit
Sub Test()

Dim MyRange As Range, Cell As Range
Dim Temp As String
Dim Total_Rows As Long

Total_Rows = Cells(Rows.Count, 3).End(xlUp).Row

Set MyRange = Range("A1:C" & Total_Rows)
For Each Cell In MyRange
    Cell.Value = AddShrimp(Cell.Value)
Next Cell

End Sub

'Bubba Gump Function
Public Function AddShrimp(InputValue As String) As String
    AddShrimp = InputValue & " Shrimp"
End Function

Before: before_script

After: after_script

ORIGINAL RESPONSE: Make sure you define the Range you're going to iterate through like this:

For Each C In Range("A3:C" & Total_Rows)
     C.Value = FixID(C.Value)
Next C

I would probably add Option Explicit to the top of your routine as well, and declare all your variables up-front too (to prevent confusion, typo-related errors etc.):

Option Explicit
Sub Test()

Dim Total_Rows As Long
Dim C As Range, TotalRange As Range

Total_Rows = Cells(Rows.Count, 3).End(xlUp).Row
Set TotalRange = Range("A3:C" & Total_Rows)

For Each C In TotalRange
    C.Value = FixID(C.Value)
Next C

End Sub
Sign up to request clarification or add additional context in comments.

4 Comments

It does not return any errors, just doesn't put the new value in the cell.
Interesting... I wrote a trivial AddShrimp function and it iterated right through without issue. (See my updated response above.)
Can you share more about your target worksheet and FixID function?
My issue was I had c = FixID(c.value) . It needed to be c.Value = FixID(c.value) . I agree that defining variables is good practice though. Thanks for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.