I'm using Excel VBA to insert an HLOOKUP function at the end of a given row. I've been attempting to use the R1C1 functionality in VBA for inserting the HLOOKUP function, which should appear as follows in Excel:
=HLOOKUP(D2,'DM NYASSOV'!3:34,32,0)
My issue is that I need the HLOOKUP to be dynamic enough that it can reference variables from the same row on which the HLOOKUP function is to be pasted.
Currently my VBA reads as follows:
ThisWorkbook.Sheets(selectTab).Cells(r, 21).FormulaR1C1 = "=HLOOKUP(RC[-17],'DM RC[-19]!'RC[2]:RC[3],RC[3]-RC[2]+1,0)"
RC[-17] references the variable I'm looking for;
RC[-19] is the underlying book/tab identifier;
RC[2] contains the initial row value, and
RC[3] contains the final row reference range.
My main issue is with correctly identifying the dynamic range selection:
'DM NYASSOV'!3:34 / 'DM RC[-19]!'RC[2]:RC[3]
Any pointers are greatly appreciated.
I think you have a few issues here. First is using VBA to dynamically build a formula that then calculates a third value that then gets used in the formula which finally calculates a result. This seems like an unnecessary amount of runaround for a value that can be done with either a formula built on the front end or calculated via VBA in the back end. The second is all the dynamic lookup of it all. It's not so much a problem, but rather a lot to keep track of as you jump through the four hoops. Just the same...
The first parameters of your HLOOKUP can either be a value like "SM1804" or a reference to a cell that contains "SM1804". You can either use VBA to bring this value directly into the formula and save Excel some processing by having to lookup that value at formula processing time:
ThisWorkbook.Sheets(selectTab).Cells(r, 21).FormulaR1C1 = "=HLOOKUP(" & Sheets(selectTab).Cells(r, 21).Offset(0, -17).value & ",'DM RC[-19]!'RC[2]:RC[3],RC[3]-RC[2]+1,0)"
Or you can stick the reference to the cell in there (which is what you are doing now):
ThisWorkbook.Sheets(selectTab).Cells(r, 21).FormulaR1C1 = "=HLOOKUP(RC[-17],'DM RC[-19]!'RC[2]:RC[3],RC[3]-RC[2]+1,0)"
On to the second parameter... I believe you have a sheet name in DM!RC[-19] This is totally OK, but you'll need to use 'Indirect' to get that sheet name into the HLOOKUP formula:
ThisWorkbook.Sheets(selectTab).Cells(r, 21).FormulaR1C1 = "=HLOOKUP(RC[-17],Indirect("'" & DM!RC[-19] & "'!RC[2]:RC[3]"),RC[3]-RC[2]+1,0)"
...this is where things get a little tricky. If, for instance, in DM!RC[-19] you have the sheetname "Sheet1" then indirect is going to return: 'Sheet1'!RC[2]:RC[3] and your HLOOKUP will use that range to do the lookup... Doesn't make a lot of sense to do a HLOOKUP on a range with two cells. So I assume that you have number values in RC[2] and RC[3] there that represent rows. So really the indirect would have to look like:
ThisWorkbook.Sheets(selectTab).Cells(r, 21).FormulaR1C1 = "=HLOOKUP(RC[-17],Indirect("'" & DM!RC[-19] & "'!R" & RC[2] & "C:R" & RC[3] & "C"),RC[3]-RC[2]+1,0)"
Now if your RC[2] has the value "4" and your RC[3] has the value "20" your indirect will return: 'Sheet1'!R4C:R20C and your HLOOKUP will use that value as the range in which it will look up.
You are also doing some math on those values in RC[2] and RC[3], so that's probably all good and doesn't need to be changed. You just need to keep in your head what VBA is going to return as a formula, and then what that formula is going to get from Indirect and then what the resulting HLOOKUP is going to find.
It's a lot to keep track of and may be simplified just by writing the formulas directly in the cell and copying down, or just doing the HLOOKUP functionality directly in VBA.
Related
I'm attempting to convert the formulas in a sheet into VBA code in a macro, and am stumped by the following:
{=IF(ISNA(MATCH($A8&$B8&$C8&E$7,'Raw Data'!$E:$E&'Raw Data'!$D:$D&'Raw Data'!$C:$C&'Raw Data'!$G:$G,0)),"","Yes")}
It's trying to look at multiple columns in one sheet, compare them to another, and see if the value of the column header is in the fourth column "G" to return "Yes" or blank. I've attached a screenshot of the sheet it fills out:
This array formula will take a long time to compute, since each column has over one million rows. Array formulas should not use whole column references.
The same result can be returned with a non-array formula, which can be used in VBA without any special commands.
=IF(ISNA(MATCH($A8&$B8&$C8&E$7,Index('Raw Data'!$E$1:$E$1000&'Raw Data'!$D$1:$D$1000&'Raw Data'!$C$1:$C$1000&'Raw Data'!$G$1:$G$1000,0),0)),"","Yes")
If you want to use an array formula in VBA, you will need .FormulaArray instead of .Formula or .FormulaR1C1
If you don't want to enter a formula into a worksheet cell, but perform the calculation in VBA, you can use Worksheetfunction (https://learn.microsoft.com/en-us/office/vba/api/excel.worksheetfunction) to use the worksheet functions and their syntax.
This is my first post and I can't find an exact answer anywhere. I have an Excel spreadsheet that is becoming too large to operate because I have long formulas in millions of cells. I need to know how to calculate the formula using VBA but have only the value appear in Excel. An example is I want to multiply column B by column C:
I have tried this code:
Range("D3:D6").Formula = Evaluate("=B3*C3")
It correctly calculates for the first cell, but for the other cells it still tries to calculate B3*C3 as a fixed reference rather than as a dynamic references that changes as the cell position changes.
How could I fix this? Thankyou.
Edit:
My actual spreadsheet looks like this:
This formula needs to be applied down 17520 rows and across 300 columns, but I only want the values to appear in Excel. The purpose of this is to reduce file size and reduce calculation time.
=IF(-SUMIF(AIG$4:AIG4,"<0")>0.9*SUMIF(AIG$4:AIG4,">0"),0,IF(-SUMIF(AIG$4:AIG4,"<0")-IF(WQ5<'Battery Specs'!$B$13,-'Battery Specs'!$B$15,IF(WQ5=ROUNDDOWN('Battery Specs'!$B$13,0)+1,-('Battery Specs'!$B$13-ROUNDDOWN('Battery Specs'!$B$13,0))*'Battery Specs'!$B$15,0))>0.9*SUMIF(AIG$4:AIG4,">0"),-(0.9*SUMIF(AIG$4:AIG4,">0")+SUMIF(AIG$4:AIG4,"<0")),IF(WQ5<'Battery Specs'!$B$13,-'Battery Specs'!$B$15,IF(WQ5=ROUNDDOWN('Battery Specs'!$B$13,0)+1,-('Battery Specs'!$B$13-ROUNDDOWN('Battery Specs'!$B$13,0))*'Battery Specs'!$B$15,IF((0.9*SUMIF(AIG$4:AIG4,">0")+SUMIF(AIG$4:AIG4,"<0"))>'Battery Specs'!$B$10,0,IF(((0.9*SUMIF(AIG$4:AIG4,">0")+SUMIF(AIG$4:AIG4,"<0"))+$AIF5*0.9)>'Battery Specs'!$B$10,'Battery Specs'!$B$10-(0.9*SUMIF(AIG$4:AIG4,">0")+SUMIF(AIG$4:AIG4,"<0")),$AIF5))))))
Try
Range("D3:D6").Formula = "=B3*C3"
Range("D3:D6").Value = Range("D3:D6").Value
or simply
Range("D3:D6").Formula = Evaluate("(B3:B6)*(C3:C6)")
Using Evaluate to calculate the formulas and then transfer the values to Excel will be slower than having Excel calculate the formulas directly.
Here are a couple of things you could try:
a) Formulas
You only have 5 million formulas in 5 million cells - this is not an overwhelmingly large number but your formulas are very long and each formula references a large number of cells.
Your formula contains many repeated expressions and calculations - move them out to helper cells and try to simplify/shorten your formula.
b) VBA - don't use Evaluate - just grab the range of 5 million cells into a single variant array and use VBA Loops, arithmetic and logic to accomplish the same task as your formulas and then put the array back.
I believe best option is to keep formulas instead of using VBA to produce same formulas. Instead, when entering new data in SpreadSheet, be sure to set calculations to manual (go to Formulas tab=>Calculation Options=>Manual. This way you wont trigger calculations when entering/pasting new values, meaning your Excel file will operate just as fast as if there was no formulas. After you entered/pasted all new values, set Calculations to Automatic.
You might want to try this:
Dim i as Integer
For i = 3 to 6
Range("D" & i).Value = Range("B" & i).Value * Range("C" & i).Value
Next i
The other alternative is to name your formula, for instance, instead of saying =B3*C3, you can give it a name say times value, and then say =timesvalue. Next, remove the formula and leave the value only. E.g. range("D3:D30").value=range("D3:D30").value
I would like to put the below coding into a vba like a function. There is a bunch of data created already by VBA, and when the VBA does its work, then the following function should be run, but i dont know how to add to my vba so that the function always runs as long as data contains. The macro i created already puts the datasheet together, now instead of creating the below with lenthy codings, i just want my macro to run the below, like a man who clicks on the below right hand corner of the cell which contains the below function.
It should be something: Activesheet.ForulaR1C1 = "=RIGHT(AY4,LEN(AY4)-FIND(".",AY4))" something. Can someone help me? Thanks
ORIGINAL FUNCTION TO BE RUN "=RIGHT(AY4,LEN(AY4)-FIND(".",AY4))"
This is where I am at now:
Sub Project_numbers()
Dim j As Integer
Zorro = Range("AY" & Rows.Count).End(xlUp).Row
o = 4
Worksheets("MJE").Range("AF" & o).FormulaR1C1 = "=RIGHT(AE4,LEN(AE4)-FIND(".",AE4))"
o = o + 1
End Sub
You have a couple of problems here. The biggest is that you've got quotation marks in your formula. VBA reads these as the end of the string, so it's interpreting your formula as two separate text strings: =Right(AE4,LEN(AE4)-FIND( and ,AE4)), separated by a .. This isn't a structure VBA can do anything with, so it's going to fail at that point.
When you're inserting a formula with VBA that contains quotation marks, you need to use two quotes together to indicate that it's a literal quote mark that's part of the string, rather than the end of the string:
"=RIGHT(AE4,LEN(AE4)-FIND(""."",AE4))"
The second problem is that you're using the FormulaR1C1 method, which expects cell references to be given in R1C1 (row#column#) notation, rather than A1 notation, but then passing it a formula that uses A1 notation. Again, this is going to confuse the issue and produce errors.
I'm guessing you used the macro recorder to get the syntax, then inserted your own formula? The macro recorder, for some weird reason, loves to use the R1C1 reference style, but we can use a different method for written code.
The full line you need is:
Worksheets("MJE").Range("AF" & o).Formula = "=RIGHT(AE4,LEN(AE4)-FIND(""."",AE4))"
EDITED TO ADD:
With further information, specifically that you need the range referenced to change as you loop, you have some options on how to do it.
1. Use the R1C1 reference style
This allows you to include relative references in formulae easily. You'll use R to designate the formula's row, and C to designate its column; so a cell that referred to itself would simply be =RC. You can follow the R and C with numbers to designate specific rows and columns, so cell B2 would be =R2C2 - row 2, column 2. More usefully, you can use =R[#]C[#] to offset your formula by a certain amount.
In your formula, assuming it's always going to be looking at column AE but whichever row the formula is entered into, your line would be:
Worksheets("MJE").Range("AF" & o).FormulaR1C1 = "=RIGHT(RC31,LEN(RC31)-Find(""."",RC31))"
2. Build your formula from variables.
You already have a variable you can use, o, so we can combine that with the rest of the string to get the appropriate references. It's harder to read, though...
Worksheets("MJE").Range("AF" & o).Formula = "=RIGHT(AE" & o & ",LEN(AE" & o & ") - FIND(""."",AE" & o & "))"
Personally, I find this method rather cumbersome to work with, but it's an option.
3. Assign the formula to your entire range as a single operation
Personally, I prefer this option; I find it to be the neatest one. I'm assuming, from your formula, that your data starts on row 4, and you want the formula to go into every cell between AE4 and the end of your data, which is stored in Zorro. You can use this line to add the formula in one go:
Worksheets("MJE").Range("AF4","AF" & Zorro).Formula = "=RIGHT(AE4,LEN(AE4)-FIND(""."",AE4))"
The cell references will update automatically for each row. There's no need for a loop with this method - of course, if you're looping anyway, that may be no great saving.
I'm just wondering if this is possible to do without a loop - In my excel sheet, in, say, Range("A1:C10") I have text concatenation formulas that, once concatenated, create real Excel functions.
As a stupid example, suppose I had the following in cell A1:
A1: ="=Sum(D"&C2&":E"&C3&")"
Now, I know in VBA I can do something along the following for any one specific cell:
Range("A1").Formula = Range("A1").Text
And it will convert my text formula into an Excel formula and evaluate it.
Now, what I'm curious about is, whether there a way to say, for example:
Range("A1:C10").Formula = Range("A1:C10").Text
Without looping through each cell individually?
Also, I can't use INDIRECT() as, unfortunately, my formulas refer to closed workbooks :/
Any ideas??
Range.Text contains the string representation of the cell's value. The actual calculated value (which I suspect is what you're after) is accessed using Range.Value - try this:
Range("A1:C10").Formula = Range("A1:C10").Value
Not sure if this is what you are trying to do, but if for example you use:
Range("A1:C10").Formula = "=Sum(D1:E1)"
then the relative references will be auto adjusted:
A1: =Sum(D1:E1)
A2: =Sum(D2:E2)
B1: =Sum(E1:F1)
... etc.
I'm running into a (run-time error '1004': Application-defined or object-defined error) error while trying to write my first Excel VBA Macro. I've looked at similar questions on stack overflow and other sites, but my issue seems to be more basic than issues others are having.
Currently, I'm trying to take the data from two cells from one sheet and write them to another sheet. I understand that trying to find the column or row of a cell that I reference by cell or row is unnecessary, but eventually I will use for-loops and will substitute the specific cell references with variables.
Here are the two lines of code that I have:
Worksheets("Sheet2").Range("A1").Value = Worksheets("Sheet1").Range("A" & Worksheets("Sheet1").Range("B2").Row).Value
Worksheets("Sheet2").Range("B1").Value = Worksheets("Sheet1").Range(Worksheets("Sheet1").Range("B2").Column & "1").Value
The first line runs fine. It writes Sheet1's A2 to Sheet2's A1.
The second line does not run, does not write Sheet1's B1 to Sheet2's B1, references the error, and I'm not sure why.
Thank you for your time and help!
The .Columns property returns an integer, not a letter. Use the Range.Cells property if you want to define a range with a numerical row and numerical column.
Worksheets("Sheet2").Range("B1").Value = Worksheets("Sheet1").Cells(1, Range("B2").Column).Value
I suppose there is a larger purpose to this but as it sits, it is very verbose code.
your last lines from your question say that you want to fill Sheet2-A1 with Sheet1-A2 and Sheet2-B1 with Sheet1-B1
the most straightforward way is
Worksheets("Sheet2").Range("A1") = Worksheets("Sheet1").Range("A2")
Worksheets("Sheet2").Range("B1") = Worksheets("Sheet1").Range("B1")
I am a beginner at VBA just like you. You don't need to know everthing in VBA to make productive use of it. I made my first macro by RECORDING it, and it worked (but was hopelessly inefficient).
I had a problem similar to yours: looking up data on another worksheet. I created the following function:
Function GetMyNumber(C3ll)
MyCol = C3ll.Column
GetMyNumber = MyCol
End Function
To use it in a spreadsheet, just enter the formula into some cell, like D5,
=GetMyNumber(D5)
When you recalculate, the number 4 appears in cell D5. If you copy cell D5 into Cell F3, you will see in F3, =GetMyNumber(F3), and calculate will return a 6. Of course you can fill down or across, the argument is changed to the cell the formula is in. And if you want, you can offset with an argument referring to any cell.
Once you get this working, you can insert the code to do you matching and other tasks that make use of your column number MyCol to extract the number from the other worksheet. Remember, MyCol is an integer.
Hopes this helps.