Convert part of Formula from Relative to Absolute Reference - excel

Originally I wanted to change parts of a formula in every 82th row where the formula looks like
=SUMIFS($BJ:$BJ;$BO:$BO;$BI7382;$A:$A;"<="&$A7382;A:A;">"&A7383)
So I wanted to change each formula for a thousand of rows from (...;$BI7382;...;"<="&$A7382;...) to:
(...;$BI$7382;...;"<="&$A$7382;...) where $7382 is always one row before the row that includes the formula above.
So the next row with this formula would be $7464 where my code should change from (...;$BI7463;...;"<="&$A7463;...) to:
(...;$BI$7463;...;"<="&$A$7463;...) and so on.
I had success with your code
For i = 7383 To Cells(Rows.Count, 1).End(xlUp).Row Step 82
Cells(i, 1).Formula = Replace(Cells(i, 1).Formula, "$BI" & i - 1, "$BI$" & i - 1)
Cells(i, 1).Formula = Replace(Cells(i, 1).Formula, "$A" & i - 1, "$A$" & i - 1)
But: There is a single column which has cells with
=SUMIFS($BJ:$BJ;$BO:$BO;$BI7382;$A:$A;<="&$A7382;A:A;">"&$A7383)
where the last value has changed from
">"&A7383to">"&$A7383
such that the last two values both have absolute column references
Because the code finds two values with $A... the replace function does not work properly
(Cells look like =SUMIFS($BJ:$BJ;$BO:$BO;$BI7382;$A:$A;"<="&$A7382;A:A;">"& after the code is executed

The problem is that the string "SUMIFS($BI" & cl.Row - 1 does not exist in your formula, so nothing gets replaced. Try the following line, it should work.
cl.Formula = Replace(cl.Formula, "$BI" & cl.Row - 1, "$BI$" & cl.Row - 1)
Now, it is better to declare the variable i as an Integer since it is used as a row index, and row indexes are integers. That way we avoid inaccuracy of Double (i.e. floating-point) arithmetic.
Dim i As Integer
In the For loop, i starts at 7383 and is incremented by steps of 81. This is good. However, i is not used anywhere in the replace statement. But the For Each loops through all rows of column O. The For Each is not needed. You can access cells in column O with Cells(i, 15). So the For loop becomes:
For i = 7383 To Cells(Rows.Count, 1).End(xlUp).Row Step 81
Cells(i, 15).Formula = Replace(Cells(i, 15).Formula, "$BI" & i - 1, "$BI$" & i - 1)
Next i
The upper bound value of i in the For loop is determined by the contents of column A. If column A has fewer rows than column O, then some replacements may be missed.

Related

Why does this loop not carry out all steps each time?

I’ve been writing a macro to format spreadsheets based on client preference. The part of the macro I’m having trouble with is getting percentage columns to format as percentages with one place after the decimal. In the code below, I determine where my % column will be (they’re headed with ‘Cov’ on the file I’m working in), and once that column is identified, the macro loops thru each row in the column and enters the % formula until the last row is reached.
Everything works mostly as intended, except the last two (2) columns that get the % formula do NOT update to show one place after the decimal. Can anyone provide insight to why the last two columns don't update the same as the others that are part of the loop?
Thank you!
For C = 24 To LastColumn + 2
If .Cells(12, C) = "Cov" Then
For i = 13 To LastRow
Set formatCell = .Range(.Cells(i, C), .Cells(i, C))
formatCell.Value = "=IFERROR(" & .Cells(i, C - 1).Address & "/" & .Cells(i, 14).Address & "*100,0)"
formatCell.NumberFormat = "0.0"
Next i
End If
Next C

Copying a Range from one Sheet to Another with Variables

This is my code:
If AssociateNameArray(ArrayLoop) = ThisWorkbook.Sheets(i).Cells(3, CompareCounter).Value Then
If i = 2 Then
Sheets(i).Range(CompareCounter & "6:" & CompareCounter & "12").Copy Destination:=Sheets(1).Range((ArrayLoop + 4) & "2")
Sheets(i).Range(CompareCounter & "14:" & CompareCounter & "28").Copy Destination:=Sheets(1).Range((ArrayLoop + 4) & "9")
CompareCounter = CompareCounter + 1
End If
End If
It gives
1004 error
Basically I am walking through a set range where CompareCounter is the column number. (stupid name, I know) I have names in an array and it is comparing the values of the array to cells in a row and when it finds a match it copies a set range back to the person's column on the main page at a certain row. The person's column number should be ArrayLoop + 4, as they start in column E. I will walk through each sheet (i) and when I find matches I will take the ranges from that sheet and copy it to the main page.
This is what causes the 1004 error: Range((ArrayLoop + 4) & "2")
If ArrayLoop is 4, then once it is evaluated to something, then it looks like this Range(52) and this is no valid range, returning 1004.
In general, try to debug the code step-by-step with F8 and always look at the values of the variables.

Create new Excel rows based on column data

Good afternoon all,
I have an issue where I have users who have multiple bank account details. I need to try and create a new row for each employee who has more than one bank account, with the second bank account being allocated a new row.
Employee Number User ID BSB Account number
10000591 WOODSP0 306089,116879 343509,041145273
10000592 THOMSOS0 037125 317166
I need it to look something like this:
Employee Number User ID BSB Account number
10000591 WOODSP0 306089 343509
10000591 WOODSP0 116879 041145273
10000592 THOMSOS0 037125 317166
Any thoughts? Your input is greatly appreciated!
Screenshots are here to demonstrate:
Right click on the tab and choose "View Code"
Paste this code in:
Sub SplitOnAccount()
Dim X As Long, Y As Long, EmpNo As String, UserID As String, BSB As Variant, AccNo As Variant
Range("F1:I1") = Application.Transpose(Application.Transpose(Array(Range("A1:D1"))))
For X = 2 To Range("A" & Rows.Count).End(xlUp).Row
EmpNo = Range("A" & X).Text
UserID = Range("B" & X).Text
BSB = Split(Range("C" & X).Text, ",")
AccNo = Split(Range("D" & X).Text, ",")
For Y = LBound(AccNo) To UBound(AccNo)
Range("F" & Range("F" & Rows.Count).End(xlUp).Row).Offset(1, 0).Formula = EmpNo
Range("G" & Range("G" & Rows.Count).End(xlUp).Row).Offset(1, 0).Formula = UserID
Range("H" & Range("H" & Rows.Count).End(xlUp).Row).Offset(1, 0).Formula = BSB(Y)
Range("I" & Range("I" & Rows.Count).End(xlUp).Row).Offset(1, 0).Formula = AccNo(Y)
Next
Next
End Sub
Close the window to go back to excel
Press ALT-F8
Choose SplitOnAccount and click run.
Note, this is going to populate the split data to rows F to I, make sure there is nothing in there. If there is post back and we can change it.
Also format columns F - I as text before you run it or Excel will strip leading zeros off as it will interpret it as a number.
Here is another sub that appears to perform what you are looking for.
Sub stack_accounts()
Dim rw As Long, b As Long
Dim vVALs As Variant, vBSBs As Variant, vACTs As Variant
With ActiveSheet '<-define this worksheet properly!
For rw = .Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
vVALs = .Cells(rw, 1).Resize(1, 4).Value
vBSBs = Split(vVALs(1, 3), Chr(44))
vACTs = Split(vVALs(1, 4), Chr(44))
If UBound(vBSBs) = UBound(vBSBs) Then
For b = UBound(vBSBs) To LBound(vBSBs) Step -1
If b > LBound(vBSBs) Then _
.Rows(rw + 1).Insert
.Cells(rw - (b > LBound(vBSBs)), 1).Resize(1, 4) = vVALs
.Cells(rw - (b > LBound(vBSBs)), 3).Resize(1, 2).NumberFormat = "#"
.Cells(rw - (b > LBound(vBSBs)), 3) = CStr(vBSBs(b))
.Cells(rw - (b > LBound(vBSBs)), 4) = CStr(vACTs(b))
Next b
End If
Next rw
End With
End Sub
I was originally only going to process the rows that had comma delimited values in columns C and D but I thought that processing all of them would allow the macro to set the Text number format and get rid of the Number as text error warnings and keep the leading zero in 041145273.
        
You Can definitely use Power Query to transform the data to generate new rows using split column option.
Check this article it explains the process in detail.
Load Data in Power Query section of excel.
Create an Index (Not required step)
Use Split column function with advance options and split them into new rows.
Save this result into new table for your use.
I did it myself and it worked like a charm.
A formula solution:
Delimiter: Can be a real delimiter or an absolute reference to a cell containing only the delimiter.
HelperCol: I have to use a helper column to make it work. You need to give the column letter.
StartCol: The column letter of the first column containing data.
SplitCol: The column letter of the column to be splitted.
Formula1: Used to generate the formula for the first column not to be splitted. You can fill this formula down and then fill to right.
Formula2: Used to generate the formula for the column to be splitted(only support split one column).
Formula3: Used to generate the formula for the Helper column.
(If the title of the column to be splitted contains the delimiter, you must change the first value of the helper column to 1 manually.)
Formula1:=SUBSTITUTE(SUBSTITUTE("=LOOKUP(ROW(1:1),$J:$J,A:A)&""""","$J:$J","$"&B2&":$"&B2),"A:A",B3&":"&B3)
Formula2:=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE("=MID($M$1&LOOKUP(ROW(A1),$J:$J,F:F)&$M$1,FIND(""艹"",SUBSTITUTE($M$1&LOOKUP(ROW(A1),$J:$J,F:F)&$M$1,$M$1,"&"""艹"",ROW(A2)-LOOKUP(ROW(A1),$J:$J)))+1,FIND(""艹"",SUBSTITUTE($M$1&LOOKUP(ROW(A1),$J:$J,F:F)&$M$1,$M$1,""艹"",ROW(A2)-LOOKUP(ROW(A1),$J:$J)+1))-FIND(""艹"",SUBSTITUTE($M$1&LOOKUP(ROW(A1),$J:$J,F:F)&$M$1,$M$1,""艹"",ROW(A2)-LOOKUP(ROW(A1),$J:$J)))-1)&""""","$M$1",IF(ISERROR(INDIRECT(B1)),""""&B1&"""",B1)),"$J:$J","$"&B2&":$"&B2),"F:F",B4&":"&B4)
Formula3:=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE("=SUM(E1,LEN(B1)-LEN(SUBSTITUTE(B1,$H$1,"""")))+1","B1",B4&1),"$H$1",IF(ISERROR(INDIRECT(B1)),""""&B1&"""",B1)),"E1",B2&1)
Helper must filled one row more than the data.
How to use:
Copy the formula generated by the above three formula.
Use Paste Special only paste the value.
Make the formula into effect.
Fill the formula.
Bug:
Numbers will be converted to Text. Of course you can remove the &"" at the end of the formula, but blank cells will be filled with 0.
ps. This method may by very hard to comprehend. But once you master it, it can be very useful to solve relative problems.

Identify and duplicate unique rows

I have files of data with the following format:
In column A, identifiers occur either doubly (e.g. 302_60) or singularly (e.g.310_58). Additional information is present in column B.
What I want to do is:
tag the rows that have single identifiers in column A with
TRUE/FALSE in Column C
for any TRUE tag, insert a line BELOW
copy into the inserted row the contents of the ENTIRE tagged row (here just columns A,B)
I solved #1 using =COUNTIF(A:A, A1)=1
I then wrote a VBA script to solve #2
Sub ins_below_and_copy()
Dim c As Range
For Each c In Range("C1:C100")
If InStr(1, c, "TRUE", vbTextCompare) > 0 Then
Rows(c.Offset(1, 0).Row & ":" & c.Offset(1, 0).Row).Insert Shift:=xlDown
End If
Next c
End Sub
Achieving the desired end result (#3)
seems simple enough, right? I have been trying .Copy and .Paste commands, but keep getting type-mismatch errors, an error that does not make sense to me (since I am not a competent VBA coder). Any ideas?
You have down all the hard work, filling in the gaps is easy. Select the two columns, HOME > Editing - Find & Select, Go To Special..., Blanks, OK, =, UP and Ctrl+Enter.
You can run this after you have your empty rows created.
Dim sheet As String
Dim lastRow As Long
sheet = "SheetName"
lastRow = Sheets(sheet).Range("A" & Rows.Count).End(xlUp).Row
For r = 2 To lastRow 'Assuming you have a Header Row
If Sheets(sheet).Cells(r, 1) = "" Then
Sheets(sheet).Cells(r - 1, 3) = "FALSE"
Sheets(sheet).Cells(r, 1) = Sheets(sheet).Cells(r - 1, 1)
Sheets(sheet).Cells(r, 2) = Sheets(sheet).Cells(r - 1, 2)
Sheets(sheet).Cells(r, 3) = Sheets(sheet).Cells(r - 1, 3)
End If
Next r

Excel VBA - Loop through range and set formula in each cell

I've got a workbook where I have one worksheet which contains a lot of data.
My goal is to create a macro that inserts a formula in a separate sheet to copy the data from the first sheet. Lets call the first sheet "Numbers1" and the second sheet "TidyNumbers1".
In the sheet "TidyNumbers1" I want to loop through each cell from column A to M and rows 1 to 60. So I've got a macro that so far looks like this:
Sub updateFormulasForNamedRange()
Dim row, col, fieldCount As Integer
colCount = 13
RowCount = 60
For col = 1 To colCount
For row = 1 To RowCount
Dim strColCharacter
If col > 26 Then
strColCharacter = Chr(Int((row - 1) / 26) + 64) & Chr(((row - 1) Mod 26) + 65)
Else
strColCharacter = Chr(row + 64)
End If
Worksheets("TidyNumbers1").Cells(row, col).Formula = "=IF(Numbers1!E" & col & "<>0;Numbers1!" & strColCharacter & row & ";"")"
Next row
Next col
End Sub
But the formula is supposed to looks like this for Column A, row 2:
IF(Numbers1!E2<>0;Numbers1!A2;"")"
And the formula in Column A, row 3 should look like this:
IF(Numbers1!E3<>0;Numbers1!A3;"")"
Formula in Column B, row 2 should look like this:
IF(Numbers1!E2<>0;Numbers1!B2;"")"
In other words, the formula looks to see if the value in Column E, row % is anything but 0 and copies it if conditions are met.
But, I see that I need to translate my integer variable Row with letters, because the formula probably needs "A" instead of 1. Also, I get a 1004 error (Application-defined or object-defined error) if I just try to use:
Worksheets("Numbers1").Cells(row, col).Formula = "=IF(Numbers1!E" & row & "<>0;Numbers1!" & col & row & ";"")"
I clearly see that the integer row should be translated to letters, if that's possible. Or if anyone has any other suggestions that might work. Also, the 1004 error is unclear to me why happens. I can define a string variable and set the exact same value to it, and there's no error. So it's probably the formula bar that whines about it I guess?
Here is a former post of mine containing functions for conversion of column numbers to letters and vice versa:
VBA Finding the next column based on an input value
EDIT: to your 1004 error: Try something like this:
=IF(Numbers1!E" & row & "<>0,Numbers1!A" & row & ","""")"
(use ; instead of ,, and "" for one quotation mark in a basic string, """" for two quotation marks).
Would not it be easier to get the cell address with the Cells.Address function?
For example:
MsgBox Cells(1, 5).Address
Shows "$E$1"
Best Regards

Resources