Referring to OTHER cells in relation to CURRENT cell in loop - vba

I have a data document i'm working on but some things on it are wrong so i need to overwrite specific cells automatically. I'm looking to set up a loop that goes through each cell in column G and if a certain value is present then insert a formula into the cell in the same row but in column J. I've got as far as setting up the loop but I don't know how to put the formula in the new cell and relate it to the current cell. I was thinking R[]C[] formulas may be the way to go but think this becomes confusing when the formula in not straightforward e.g VLOOKUPS with IFs and MATCHES etc...
Sub FindDefects()
Dim RngCl As Range
Dim Rngg As Range
Set Rngg = Sheet1.Range("A1:A6")
For Each RngCl In Rngg.Cells
If RngCl.Value = "TEXT" Then
RngCl.Offset(0,3).FormulaR1C1 = "R[0]C[-1]/R[0]C[3]"
Else
'Nada
End If
Next RngCl
End Sub
I'm not sure really where to go from here, especially how to add in formulas such as:
=IF(LEN(J9)>0,J9*VLOOKUP(M9,Core!A:C,3,FALSE)/VLOOKUP(K9,Core!A:C,3,FALSE),P9)
Instead of R1C1 formulas. Any help on moving forward is appreciated!

Related

VBA creating formulas referencing a range

After several hours of research, I still can't solve what seems to be a pretty simple issue. I'm new to VBA, so I will be as specific as possible in my question.
I'm working with a DDE link to get stock quotes. I have managed to work out most of the table, but I need a VBA to create a finished formula (i.e., without cell referencing) in order to the DDE link to work properly.
My first code is as follows:
Sub Create_Formulas()
Range("J1").Formula = "=Trade|Strike!" & Range("A1").Value
End Sub
Where J2 is the blank cell and A2 contains the stock ticker. It works fine, but when I try to fill out the rows 2 and bellow, it still uses A1 as a static value.
Sub Create_Formulas()
Dim test As Variant
ticker = Range("A1").Value
'Test to make variable change with each row
'Range("J1:J35").Formula = "=Trade|Strike!" & Range("A1:A35").Value
'not working
Range("J1:J35").Formula = "=Trade|Strike!" & ticker
'not working
End Sub
I couldn't find a way to solve that, and now I'm out of search queries to use, so I'm only opening a new topic after running out of ways to sort it by myself. Sorry if it is too simple.
You are referencing absolute cell adresses here. Like you would do when using $A$1 in a normal excel formula.
What you want to do is:
Dim row as Integer
For row = 1 to 35
Cells(row,10).Formula = "=Trade|Strike!" & Cells(row,1).Value
Next row
This will fill the range J1 to J35 with the formula. Since (row,10) indicates the intersection of row and column 10 (J)
Firstly, in your second set of code, you define a variable "test", but never give it a value.
You assign a value to the variable "ticker", and then never reference it.
Secondly, the value you have assigned to ticker is a static value, and will not change when it is entered in a different row.
Thirdly, I think your issue could be solved with a formula in Excel rather than VBA.
The "INDIRECT" function can be quite useful in situations like this.
Try inserting the formula
=INDIRECT("'Trade|Strike'!"&A1)
into cell A1, then copy down.
Note the ' ' marks around "Trade|Strike". This is Excels syntax for referencing other sheets.

User Inserted Rows/Columns Impacting Excel VBA

I am trying to determine how I can have a user insert columns and/or rows without it impacting the rest of the code in the macro.
Defining names for my objects and using r1c1 references in VBA does not seem to help as these inserted columns shift those references and names as well.
Am I missing something that should be completely obvious???
Or is what I am trying to accomplish not possible?
UPDATE: When I name a range in excel (without VBA) everything seems to work fine with inserted columns. However, when I name the range with VBA everything messes up. Here is a sample of some code to work with.
When this below code is run... I am not able to insert columns as my MSGBOX's don't realize the named cell has shifted to the right. HOWEVER, if I were to remove the first line in this code and just name the cell "GanttStartLocation" which is quoted out in the code... this seems to work fine.
WHY DOES THiS NOT WORK WHEN NAMED WITH VBA????
ActiveWorkbook.Names.Add Name:="DEFINENAMETEST", RefersToR1C1:="=Sheet1!R10C14"
Dim rGanttLocation As Range 'Range used to define where the Gantt chart begins
Dim iFirstRowGantt As Integer 'Defines the first row of the Gantt chart based on rGanttLocation
Dim iFirstColumnGantt As Integer 'Defines the first column of the Gantt chart based on rGanttLocation
'Set rGanttLocation = Worksheets(1).Range("GanttStartLocation")
Set rGanttLocation = Worksheets(1).Range("DEFINENAMETEST")
iFirstRowGantt = rGanttLocation.Row
iFirstColumnGantt = rGanttLocation.Column
MsgBox (iFirstRowGantt)
MsgBox (iFirstColumnGantt)
Use a named range for your cells so that addition of rows/columns are less likely to impact your code if rows/columns are added inside the range. For example: if D1-F10 was called testrange, executing the following subroutine will give red background color to the range
Public Sub Test()
Range("testrange").Interior.Color = vbRed
End Sub
If a new row and column are added to this range, and the subroutine is re-executed after replacing vbRed with vbYellow, the entire range (with new column and row) will turn yellow.
Outside of the named range, it's going to take decent amount of work to keep your Macro's generic, from what I understand.

VBA to insert and increment formulae in cell

I have this VBA
Sub ApplyCV()
Range("H2:H5000").Formula = "=GetPattern($A2)"
End Sub
Which basically applies the custom function "=GetPattern" to execute the macro of the same name. This works fine.
However, instead of explicitly stating the range (which will vary with each dataset) I'd like to increment the formula on a loop UNTIL the last row of data or until there is no cell value in A:whatever.
Any help with this would be gratefully received.
Many thanks
Try finding the last value in column A (looking from the bottom up) and using that cell's row to define the extent of the range in column H that the formula is applied to.
Range("H2:H" & cells(rows.count, 1).end(xlup).row).Formula = "=GetPattern($A2)"

Formula to remain after running macro

I was wondering how I can have a formula stay on column J2:J600. The formula is =R2 and would go all the way down to =R600. I thought I could manually put the formula in but every time I run my macro, the formulas disappear. Is there a way to embed the formula into the column? Thanks.
EDIT
Sub FormatCounsel()
Sheet2.Range("J2").FormulaR1C1 = "=RC[0]"`
Sheet2.Range("J2").AutoFill Destination:=Range("J2:J600"), Type:=xlFillDefault
End Sub
This is what I put in and I'm getting an error.
EDIT 2
Sorry I just realized that I want the formula =R2 in cells J2:J600. Sorry if I caused any confusion.
I see a big red flag in your code: you're using circular referencing! This means that you're saying J2 = J2. In other words, your formula refers to itself for a value, so it calculates to find the value, but to find the value it needs to calculate, etc...
Entering circular referencing should always give you an error when you manually enter circular referencing. However, when using VBA to enter the CR, I was only able to raise an error by setting Application.Calculation to xlCalculationManual, and then calculating the sheet.
You may have just made a typo, and that explains why there's circular referencing in your code, but I figured I'd explain it anyway. :)
R1C1 formulas use relative references to refer to cells. So when you say RC[0], you're saying that you want to use the cell in the same row and the same column. Let's see some examples. In our example, the formula will be in B2.
Dim r As Range
Set r = Range("B2")
r = "=RC" '<~~~ the equivalent to what you used in your code. Refers to B2.
r = "=R[-1]C" '<~~~ Refers to B1 (current row minus 1).
r = "=RC[1]" '<~~~ Refers to C2 (current column plus 1).
r = "=R[1]C[1]" '<~~~ Refers to C3 (current row and current column plus 1).
r = "=R[-1]C[-1]" '<~~~ Refers to A1 (current row and current column minus 1).
Now, as far as entering formulas into cells, it can be done all at once and very easily. Consider the example below:
Sub FormatCounsel()
Sheet2.Range("J2:J600") = "=RC[1]" '<~~ Each cell will refer to the cell to the right.
End Sub
Any time you write something else to those cells or clear them with the macro, you will lose those formulas. You need to find the place in your code where you are overwriting or clearing them, and modify that code. The other option is writing those formulas back to the cells at the end of the macro. You can accomplish this with:
Range("J2").FormulaR1C1 = "=RC[0]"
Range("J2").AutoFill Destination:=Range("J2:J600"), Type:=xlFillDefault

when cell contains then

I have a range: M2:M & aantalrijen. For this range, I want to have a value in each cell based on the value in the same cell in column E. I have a script which defines the total range in the workbook and I want to use that number of filled rows to fill column M with the right value. I have this script, but it doesn't work. (vba does not help me finding my mistakes). How can I make this code work? the code:
With Sheets("sheet1")
aantalrijen = .Range("A1", .Range("A1").End(xlDown)).Cells.Count
For Each cell In .Range("M2:M" & aantalrijen)
If CStr(.Cells(aantalrijen, -8)) = "*zeezout*" Then .Cells(aantalrijen, 0) = "Zeezout"
Next cell
End With
What is the right code?
I used a code a consultant created for me 2 weeks ago which filled an entire range with a formula. I tried to use this formula, but as you point out: I do not know enough of the basics. I found out again today. I have fixed it now because it was something that could be done by creating a regular excel formula. Searching on google for vba and if or vba and containts helped me create and excel formula for one cell. I then recorded it with the macro recorder to see what cell references are used and then pasted it in my macro code. –