I am trying to produce a programme such that for example if device V is found in column A, it will name the cell that is beside device V to be voltage. The same goes for other devices. Currently, im using if and for loop and i suppose it works well in this case when there are 3 devices. However, in the case where lets say there are 100 devices, i realised that i have to copy and paste then edit the code for 100 times and this can be a tedious process. So i was thinking, does using Do while loop help to improve the efficiency or is there other better way to do it?
Edit: it can also be a case where lets say i already have a list of device with its corresponding alternative name on another worksheet (not same order like can be device V and voltage on 3rd row instead of 1st row) and i am unsure how to make use of it without having to name it like what i did in my code.
After running the programme
Dim lastrowt As Long Dim t As Long lastrowt = ws1.Range("A" & Rows.count).End(xlUp).Row For t = 1 To lastrowt If ws1.Range("A" & t) = "device V" Then ws1.Range("B" & t) = "voltage" End If If ws1.Range("A" & t) = "device F" Then ws1.Range("B" & t) = "Faraday" End If If ws1.Range("A" & t) = "device k" Then ws1.Range("B" & t) = "Kelvin" End If Next
To do it with a dictionary (you must add a reference to Microsoft.Scripting.Runtime):
Sub Macro1() Dim dict As Scripting.Dictionary Dim lastrowt As Long Dim t As Long Dim ws1 As Worksheet Dim key As String Set ws1 = Sheets(1) Set dict = New Scripting.Dictionary lastrowt = ws1.Range("T" & Rows.Count).End(xlUp).Row dict.Add "device V", "Voltage" dict.Add "device F", "Faraday" dict.Add "device K", "Kelvin" For t = 1 To lastrowt key = ws1.Range("A" & t) If dict.Exists(key) Then ws1.Range("B" & t) = dict(key) End If Next End Sub
You can easily do this, using the following formula:
=IF(A:A="device V";"voltage";IF(A:A="device k";"Kelvin";"Fahrenheit"))
The usage of range
A:A assures that you can use this formula everywhere in the column.