VBA apply Formula to an entire column - excel

I want to apply an Formula into an entire Row (A)
My code:
Sub row()
Dim i As Long
Dim S1 As String
Dim S2 As String
S1 = "=+LINKS(C"
S2 = ";1)"
i = 2
Range("A1").EntireColumn.Insert
For i = 2 To 90000
Range("A" & i).Value = "=+Left(C "" & i & "" ;1)"
Next i
End Sub
The error is occuring on: Range("A" & i).Value = "=+Left(C "" & i & "" ;1)"
Error code: '1004'
i can't find a way to put the variable "i" into the Formula...
I want to put into the column "A" the Formula, which lets the Cells in "A" look into the Cell "C" of each individual row and take the first Number and write it in itself.
Thank you in advance.

Related

'Range' of object'_Global' fail in Do Until

Basically I just found this little code on the web, I thought it might help me because I want to improve it. But on the
Do Until Range("A" & amp, R) = ""
line I got the mentioned error in the title.
Here is the code:
Sub Use_Instr()
R = 1
'loop to the last row
Do Until Range("A" & amp, R) = ""
'check each cell if contains 'apple' then..
'..place 'Contains Apple' on column B
If Range("A" & amp, R) Like "*apple*" Then
Range("B" & amp, R) = "Contains Apple"
End If
R = R + 1
Loop
End Sub
It does search the "apple" term in the sentences in A column and write "contains apple" in the B
column if it contains "apple"
Try this instead:
R = 1
'loop to the last row
Do Until Range("A" & R).Value = ""
'check each cell if contains 'apple' then..
'..place 'Contains Apple' on column B
If Range("A" & R).Value Like "*apple*" Then
Range("B" & R).Value = "Contains Apple"
End If
R = R + 1
Loop
Range("A" & amp, R) is not the right way to address the range. When you copied from the website, it copied the html encoding as well. In Html & is encoded as &. Simply replace & amp, with & in your code. So your code becomes
R = 1
'loop to the last row
Do Until Range("A" & R) = ""
'check each cell if contains 'apple' then..
'..place 'Contains Apple' on column B
If Range("A" & R) Like "*apple*" Then
Range("B" & R) = "Contains Apple"
End If
R = R + 1
Loop
Also to make the code case insensitive, as suggested by #VBasic2008 in comments below, you may want to change Range("A" & R) Like "*apple*" to If LCase(Range("A" & R).Value2) Like "*apple*" Then.
Having said that, I would use a different approach than using a loop which is a slightly slower approach.
It does search the "apple" term in the sentences in A column and write "contains apple" in the B column if it contains "apple"
If you were to do this in Excel, then you would use the formula =IF(ISNUMBER(SEARCH("apple",A1)),"Contains Apple","")
So what we will do is find the last row in Column B and then add this formula in the entire range in one go! Finally we will convert the formula to values.
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
Dim sFormula As String
'~~> Change this to the relevant sheet
Set ws = Sheet1
'~~> This is your formula
' =IF(ISNUMBER(SEARCH("apple",A1)),"Contains Apple","")
sFormula = "=IF(ISNUMBER(SEARCH(""apple"",A1)),""Contains Apple"","""")"
With ws
'~~> Find the last row in column B
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Insert the formula in the entire range in 1 go
With .Range("B1:B" & lRow)
.Formula = sFormula
'~~> Convert formula to value
.Value = .Value
End With
End With
End Sub

Is there any way to step through more then one range of cells during the same For Each loop?

I am currently trying to create a loop that steps through 2 ranges of data. First range is b16-b35 next range is j16-j35. Currently I can only get 1 of the 2 loops to step through.
I started with a For While loop. Using i as a variable for 16-35. When I tried this method I couldnt get the msgbox to print the data. I moved to a For each loop. This gave me the ability to step through 1 cell but not the other.
If [D8] = 2 Then
Dim r As Range
Dim j As Range
Dim jcell As Range
Dim cell As Range
Set r = Range("B16:B35")
Set j = Range("J16:J35")
For Each cell In r
For Each hcell In j
If cell = "" Or cell = "N/A" Then GoTo ENDGAME
MsgBox "pn is " & cell & " route is " & jcell
Next jcell
Next cell
ENDGAME:
End IF
Current method causes the loop to step through all of J for each r. I have tried combining the for each loops with an and statement and it bugs the code.
It seems like really you have one loop (process), it's just that your data feels to be in two different places. Let's loop through B16:B35, referencing the corresponding values in column J as we go:
Sub looper()
Dim r As Range
Dim cell As Range
If [D8] = 2 Then
Set r = Range("B16:B35")
For Each cell In r
If cell = "" Or cell = "N/A" Then GoTo ENDGAME
MsgBox "pn is " & cell & " route is " & cell(1, 9)
Next cell
ENDGAME:
End If
End Sub
So cell is the range object, starting with B16... you can reference a different cell by its offset from a range object... cell(1, 9) means take the cell, look at the same row (1), but the 9th column (count column B as "one", column C as two; column J is nine).
It's normally a good idea to declare variables at the top of the sub, that's why I moved the Dims. Not strictly necessary for this code to work.
Use a counter as the For loop, and use that to set a reference into each range
Dim r As Range
Dim j As Range
Dim jcell As Range
Dim rcell As Range
Dim i as Long
Set r = Range("B16:B35")
Set j = Range("J16:J35")
For i = 1 to r.Rows.Count
Set rcell = r.Cells(i, 1)
Set jcell = j.Cells(i, 1)
MsgBox "pn is " & rcell.Address & " route is " & jcell.Address
Next i
Not completely sure what you are trying to do, but the following should do perform what you would like to..
Btw, defining cell as a range etc. is not best practice. it is better to give it a name other than a function, etc name.
with thisworkbook.sheets(1)
if .range("B8").value = 2 then
for i = 16 to 35
if .range("B" & i).value = "" or .range("B" & i).value = "N/A" then
goto EndGame
else
msgbox "pn is " & .range("B" & i).value & " route is " & .range("J" & i).value
end if
next i
EndGame:
end if
end with
If you want to do 2 loops, first for B , than for J, you can do this. However, if one of the cells in one of the loops contains nothing or n/a -> function will stop. If you want to go to the next (i) ; iteration. you should put the:
EndGame:
just before:
next i
--
dim First_Range_Done as boolean
with thisworkbook.sheets(1)
if .range("B8").value = 2 then
for i = 16 to 35
if First_Range_Done = false then
if .range("B" & i).value = "" or .range("B" & i).value = "N/A" then
goto EndGame
else
msgbox "pn is " & .range("B" & i).value & " route is " & .range("J" & i).value
end if
end if
if First_Range_Done = true
if .range("J" & i).value = "" or .range("J" & i).value = "N/A" then
goto EndGame
else
msgbox "pn is " & .range("B" & i).value & " route is " & .range("J" & i).value
end if
if i = 35 then exit sub
end if
if i = 35 then
First_Range_Done = true
i = 15
end if
next i
EndGame:
end if
end with
Dim r1 As Range
Dim r2 As Range
Dim u As Range
Dim res As String
Set r1 = Range("A1:B1")
Set r2 = Range("C3:D3")
Set u = Union(r1,r2)
res = ""
For Each cell In u
res = res + cell.Value2
Next cell
MsgBox res
Assuming cells have following values:
-------------------
| Address | Value |
-------------------
| A1 | a1 |
| B1 | b1 |
| C3 | c3 |
| D3 | d3 |
-------------------
You would get a1b1c3d3 as result being displayed by MsgBox.
With this method you have the added bonus, you can combine ranges of different dimensions.

How do I lookup multiple values from a comma separated cell and average the results in excel?

I'm trying to build a formula that can lookup multiple ISO country codes separated by comma contained in one cell (Cell A2, Image 1) with a reference to a list of country codes and education scoring (Columns F and G, Image 1). Then return the average of the scores of all countries on cell B2. does anyone know if I can build a formula to handle that?
I didn't think you could do this with cell formula, but then I saw this post and came up with this:
=AVERAGE(IF(ISNA(MATCH($F$2:$F$99, TRIM(MID(SUBSTITUTE(A2,",",REPT(" ",99)),(ROW(OFFSET($A$1,,,LEN(A2)-LEN(SUBSTITUTE(A2,",",""))+1))-1)*99+((ROW(OFFSET($A$1,,,LEN(A2)-LEN(SUBSTITUTE(A2,",",""))+1)))=1),99)), 0)), "", $G$2:$G$99 ))
Try pasting into cell B2 as an array formula (Ctrl + Shift + Enter) and fill-down... And don't ask me how it works.
You could try VBA:
Option Explicit
Sub test()
Dim i As Long
Dim strCode As String, strScore As String
Dim rngVlookup As Range
Dim Code As Variant
With ThisWorkbook.Worksheets("Sheet1")
Set rngVlookup = .Range("F2:G34")
For i = 2 To 3
strCode = ""
strScore = ""
strCode = .Range("A" & i).Value
For Each Code In Split(strCode, ",")
If strScore = "" Then
On Error Resume Next
strScore = Application.WorksheetFunction.VLookup(Trim(Code), rngVlookup, 2, False)
Else
On Error Resume Next
strScore = strScore & ", " & Application.WorksheetFunction.VLookup(Trim(Code), rngVlookup, 2, False)
End If
Next Code
With .Range("B" & i)
.Value = strScore
.NumberFormat = "0.000000"
End With
Next i
End With
End Sub

VBA: How to describe row with specific string

Hi I'm trying to create a loop that identifies a specific string in column "B", and SUMs up the values in column "D" of the same row. So far I've been able to identify the "cash" but now I don't know how to describe column "D" of the SAME row and sum it up. Please help!
Below is what I've got so far for this loop.
Dim CD As Long
Dim text As String
Dim Z As Long
CD = 0
For Z = 1 To Range("B" & Rows.Count).End(xlUp).Row
text = Range("B" & Z).Value
If Left(text, 4) = "Cash" Then
Sum....
You could certainly do something like:
For Z = 1 To Range("B" & Rows.Count).End(xlUp).Row
text = cells(Z,2).Value
If Left(text, 4) = "Cash" Then
Sum.... Zum = Zum + cells(Z,4).value
However, the computation could be done with a simple worksheet formula
=SUMIF(B:B,"cash*",D:D)
Following the code you have provided, this would be what you are looking for:
Sub calculateSum()
Dim CD As Long
Dim text As String
Dim Z As Long
'Create a variable to store the sum and set its value to 0.
Dim sum As Double
sum = 0
CD = 0
For Z = 1 To Range("B" & Rows.Count).End(xlUp).Row
text = Range("B" & Z).Value
If Left(text, 4) = "Cash" Then
'Increase the sum by the value stored in column D on the same row.
sum = sum + Range("D" & Z).Value
End If
Next Z
'Display the final result (sum).
MsgBox "Sum: " & sum
End Sub

Replacing Column with an Identical Column Inside a Formula

Is there any way in Excel to 'paste' a formula over a column so that each cell receiving the formula is taken as input in the formula? For example, I would like to write =Text() over a range without first putting Text(A1) over an empty column, dragging it down, and pasting the results into the original column. Is this possible? Thanks!
Here is an example that replaces a column of values with a column of formulas:
Sub Formulate()
Dim N As Long, i As Long, dq As String
N = Cells(Rows.Count, "A").End(xlUp).Row
dq = Chr(34)
For i = 1 To N
v = Cells(i, 1).Value
Cells(i, 1).Formula = "=Text(" & v & "," & dq & "mm/dd/yyyy" & dq & ")"
Next i
End Sub

Resources