Using a stored integer as a cell reference - excel

Dim x As Integer
Dim y As Integer
For y = 3 To 3
For x = 600 To 1 Step -1
If Cells(x, y).Value = "CD COUNT" Then
Cells(x, y).EntireRow.Select
Selection.EntireRow.Hidden = True
End if
If Cells(x, y).Value = "CD Sector Average" Then
Cells(x, y).EntireRow.Select
Selection.Insert Shift:=xlDown
Cells(x + 1, y - 1).Select
ActiveCell.FormulaR1C1 = "=R[0]C[1]"
Cells(x + 1, y + 1).Select
Selection.ClearContents
Cells(x + 1, y + 2).Select
Selection.ClearContents
Cells(x + 1, y + 3).Select
Selection.ClearContents
Cells(x + 1, y + 4).Select
ActiveCell.FormulaR1C1 = ***"=sum(R[This is what I need to change]C:R[-3]C"***
Cells(x + 2, y).Select
End If
I need to make the starred formula come out as a sum of a column that ends 3 rows above the Sector average row and starts the number that is displayed in a cell in the Count Row.
I tried this to no avail in the count if statement
Dim count As Integer
count = Cells(x , y).Value
And then using the count variable in the cell reference and got an error.
Any tips would help or if I'm going about this wrong let me know.

You have to find a suitable formula for entering in the target cell. Then you would build such formula with string concatenation, etc., for entering it via VBA.
One option for the formula is to use OFFSET, as in
=SUM(OFFSET($A$1,D3-1,COLUMN()-1):OFFSET($A$1,ROW()-3-1,COLUMN()-1))
This sums all values from Cell1 to Cell2, in the same column you place the formula. Cell1: at the row indicated by the value in D3, Cell2: 3 rows above the cell that contains the formula.
Another option is to use INDIRECT, as in
=SUM(INDIRECT("C"&D3):INDIRECT("C"&(ROW()-3)))
This sums all values from Cell1 to Cell2, in column C. Cell1: at the row indicated by the value in D3, Cell2: 3 rows above the cell that contains the formula.

You're already using Cells(row, col) to reference your location, so you already know exactly what row you're on. Therefore:
ActiveCell.FormulaR1C1 = "=sum(R[" & x-3 & "C:R[" & X & "]C"
will give you Row("CD Sector Average")-3 through Row("CD Sector Average"). Adjust the x-3 and x as necessary, since I'm not 100% certain which rows you need to total.
Also, now that you've used the Macro Recorder to get your basic code (a great place to start, BTW, but it will teach you terrible coding habits), go read How to avoid using Select in Excel VBA macros to learn how to clean up your code.

Related

How to highlight duplicates rows based on more than 30 columns?

I am trying to highlight duplicate rows by Excel VBA code but I'm receiving a "'Range' of Object _Global' failed" error and I'm hoping someone can help as to why.
Sub Duplicate_Row()
Dim x As Integer
Dim Y As Integer
Dim Z As Integer
x = 2
Y = x + 1
Z = 2
Do While Range("A:AA" & Y) <> ""
Z = Z + 1
Do While Range("A:AA" & Y) <> ""
If Range("A:AA" & x) = Range("A:AA" & Y) And Range("A:AA" & Y).Interior.ColorIndex = xlColorIndexNone Then
Range("A:AA" & x).Activate
Selection.End(xlToLeft).Select
Range("A" & x).Select
Range(Selection, Selection.End(xlToRight)).Select
'Selection.Interior.Color = vbYellow
Selection.Interior.ColorIndex = Z
Range("A" & Y).Select
Range(Selection, Selection.End(xlToRight)).Select
'Selection.Interior.Color = vbYellow
Selection.Interior.ColorIndex = Z
End If
Y = Y + 1
Loop
x = x + 1
Y = x + 1
Loop
MsgBox "Done"
End Sub
How to highlight duplicates in rows with msgbox ? I also want a msgbox for duplicate rows and highlight only those rows in which all the details are duplicate.
As my late father used to say "When you can do something the difficult way, then why do it the easy way?" and this is exactly what I see when reading your question. :-)
I have made a small Excel file, highlighting duplicates, using conditional formatting, as you can see in this screenshot:
(It's all about column "A", the others are just there for explanatory reasons: "B" contains the formula results, "C" contains the =FormulaText(Bn) formula.)
The formula this is based on, is: =COUNTIF($A$1:A1,A1)-1.
Some explanation: this formula (you can see the results in the second column) counts the amount of times that An (which is what you get by dragging down A1) is present in the range A1:An (the first cell A1 is fixed because of the dollar-signs in the formula), minus one (in order not to count the cell value itself. As a result, when the value gets found before (a duplicate), the value gets 1 or higher, and when the value does not get found before, you get a zero. Conditional formatting can be based on formulae: TRUE or non-values get highlighted.

How to move cells down its column based off blank cell row in range

I am trying to move cell values in columns K to L down within its column to the same row as every blank cell in column E.
Hopefully this makes sense but I think i need to figure out how to find each blank cell's row number and force it as a row variable i can then use to tell my code to move cell values in range K13:L. For example, if there's a value in K13:L14 and the blank cells in column E is E20 and E23, i want K13 and L13 to move to K20 and L20 while K14 and L14 move to K23 and L23.
The number of blank cells will always match however many cells with value are in column K/L
Would appreciate any help on this!
Use the macro below to start your studies. But first you need to remove the values in column K&L to N&O. (Maybe you can record a macro and add the recorded codes to the start of the codes below.)
Sub move_it()
i = 13
j = 13
Do While Cells(j, 14).Value <> ""
If Cells(i, 5) <> "" Then
i = i + 1
Else
Range("n" & j, "o" & j).Select
Selection.Cut
Range("K" & i).Select
ActiveSheet.Paste
j = j + 1
i = i + 1
End If
Loop
End Sub
The answer that was i needed to offset my copy paste by the rows i needed to move it to!
ws.Range("E" & openitemstartrow + 1, ws.Range("F" & openitemstartrow +
10).End(xlUp)).Copy
targetws.Range("G" & rows.Count, "H" & rows.Count).End(xlUp).Offset(1, 4).PasteSpecial Paste:=xlPasteValues

How to apply Autofill function for a dynamic range in VBA?

I'm in the process of creating a macro that should return 3 results:
adds 3 columns to the right after column C
implements characters per line counting formula which returns number of characters per line from column C in newely created column D
implements total characters count formula in column E (counts sum of characters count returned from column D)
Future Result: As current code gives formula results in cells D2 and E2 I want it to run Autofill function so that no matter the number of rows in the spreadsheet it gives results for all of them (just like double-clicking in the bottom right corner of a cell with formula).
This is how code looks like now:
Sub AutoFillTest
Columns("D:F").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove '
Range("D2").Select
ActiveCell.Formula = "=Len(Left(C2, IfError(Find(Chr(10), C2, 1), 99))) & IfError("" ,"" &
Len(Mid(C2, Find(Chr(10), A2, 1) + 1, 99)), """")"
#Here goes Autofill part which I'm looking for#
Range("D2,E2").Select
Range("E2").Activate
ActiveCell.Formula = "Len("C2")"
#Here goes Autofill part which I'm looking for#
End Sub
You can use autofill like this:
Set SourceRange = Worksheets("Sheet1").Range("A1:A2")
Set fillRange = Worksheets("Sheet1").Range("A1:A20")
SourceRange.AutoFill Destination:=fillRange
Then what you would need to is find the last row for the columns you need.
UPDATE
With your need for dynamic last row, something simple like this might work:
Add a function:
Public Function GetLastRow(str_TabName As String, lng_Column As Long, lng_Row As Long) As Long
 
Sheets(str_TabName).Select
'Range(str_Column & lng_Row).Select
Cells(lng_Row, lng_Column).Select
Selection.End(xlUp).Select
 
GetLastRow = ActiveCell.Row
 
End Function
Then amend the code like this:
Sub AutoFillTest
'' Get last row
Dim lng_LastRow as Long
'' Pass argument as required sheet, the column as a number, and the last row to start from
lng_LastRow = GetLastRow("Sheet1", 4, 100000)
Columns("D:F").Insert Shift:=xlToRight, _
CopyOrigin:=xlFormatFromLeftOrAbove '
Range("D2").Select
ActiveCell.Formula = "=Len(Left(C2, IfError(Find(Chr(10), C2, 1), 99))) & IfError("" ,"" &
Len(Mid(C2, Find(Chr(10), A2, 1) + 1, 99)), """")"
#Here goes Autofill part which I'm looking for#
Set SourceRange = Worksheets("Sheet1").Range("D2:D2")
Set fillRange = Worksheets("Sheet1").Range("D3:D" & lng_LastRow )
SourceRange.AutoFill Destination:=fillRange
Range("D2,E2").Select
Range("E2").Activate
ActiveCell.Formula = "Len("C2")"
#Here goes Autofill part which I'm looking for#
'' apply from the example above and see if it works for you
End Sub
Note I haven't checked your formulae

Comparing cells in a column (VBA)

I am trying to list the comparisons of each two cells in the same column. Say, I have some values in the cells A1,A2,A3,..,A11. I'm trying to create a table such that in each cell contains the minimum value of two Ai and Aj (i is not equal to j). i.e min(Ai,Aj)=x. However, I managed to write something that helps me to compare A1 with other Ai's. In each time, I need to change what I wrote so as to get the comparison of A2 to other cells (except A1). How can I manage to get the list once? Thanks in advance.
This is what happens when I run my code.
This is I am trying to get.
Sub comparisonfunction2()
Dim ds As Long ' number of files
Dim i As Long 'loop variable
Range("A1").Select
ds = 12
yp = Sheets("Sheet1").Range("a1").CurrentRegion.EntireRow.Count
For i = 2 To ds
If Cells(2, 1) < Cells(i + 1, 1) Then
Cells(2, 1).Select
Selection.Copy
Cells(i + 1, 5).Select
ActiveSheet.Paste
Else
Cells(i + 1, 1).Select
Selection.Copy
Cells(i + 1, 5).Select
ActiveSheet.Paste
End If
Next
End Sub
Just type =MIN($A$2,A3), drag the formula

Inserting Excel formula that refers to alternative columns

I am trying to insert the following formula ='External Costs B0'!F73 in the same row of a sheet in consecutive columns, however with the cell reference "F73" in worksheet "External Costs" referring to alternate columns e.g F73, H73, J73, L73 etc.
Here is a screen shot of the spreadsheet with formula commented
Screen Capture of formula sheet
This is the code I have tried but I am struggling to figure how to get the alternative column reference working.
Dim CostColumns As Long
'Select cell to start inserting the formula from
Range("E26").Select
'Start from column F (6) in the "External Costs B0" sheet and step to every alternate column
For CostColumns = 6 To 600 Step 2
ActiveCell.Formula = "= ""'External Costs B0'!"" & Rows(73)Columns(CostColumns)"
Move to the next cell to insert the formula in and advance the column reference by 2 columns
ActiveCell.Offset(0, 1).Select
Next CostColumns
The net result is the same error I have seen in many posts:
Application-defined or object-defined error.
Here are many other syntax's for the formula insert I have tried with no success. Any help is greatly appreciated. The below refers to row 40 instead of row 73 in the External Costs B0 sheet as per the example above.
Range("E26").Select
For CostColumns = 6 To 66 Step 2
'ActiveCell.FormulaR1C1 = "= worksheets("""External Costs B0""").Cells(40,6).Value"
'ActiveCell.FormulaR1C1 = "='External Costs B0'!R[14]C[CostColumns]"
'Range("E26:AK26").FormulaR1C1 = "='External Costs B0'!R[14]C[CostColumns]"
'ActiveCell.FormulaR1C1 = "= worksheets('External Costs B0')!" & " Rows(40)Columns(CostColumns)"
'Range("E26:AK26").FormulaR1C1 = "='External Costs B0'!R[14]C[+2]"
'Range("E26:AK26").FormulaR1C1 = "=Wksht.Cells(40,CostColumns) &"
'Range("E26:AK26").Formula = "=worksheets('External Costs B0'!)" & ".Cells(40,6)"
'ActiveCell.Formula = "= worksheets('External Costs B0'!).Cells(40,6).Value"
ActiveCell.Offset(0, 1).Select
Next CostColumns
Use this:
ActiveCell.Formula = "='External Costs B0'!" & Cells(73, CostColumns).Address(0, 0)
The problem with that is that Rows(73) and Columns(CostColumns) both return a Range object which you can't concatenate to a string.
Its way easier, if you use FormulaR1C1 and no selects like in the following sub:
(please change R, RowOffset and FormulaUntilColumn to your needs)
Sub Formulas()
Dim I As Integer
Const R As Long = 9 'row
Const RowOffset As Integer = -8
Const ForumulaUntilColumn As Long = 7
For I = 1 To ForumulaUntilColumn
Cells(R, I).FormulaR1C1 = "=R[" & RowOffset & "]C[" & I - 1 & "]"
Next I
End Sub
P.S.: add workbook and table name as in any other formula between '=' and 'R['
This code will place your formula in cells Sheet1!A1:AD1.
The formula in A1 will be ='External Costs B0'!$A$73.
In B1 it will be ='External Costs B0'!$C$73 and so on up to ='External Costs B0'!$BG$73 in cell AD1.
Sub PasteFormula()
Dim CostColumns As Long
Dim y As Long
'Starting column for External Costs reference
CostColumns = 1
With ThisWorkbook.Worksheets("Sheet1")
For y = 1 To 30
.Cells(1, y).FormulaR1C1 = "='External Costs B0'!R73C" & CostColumns
CostColumns = CostColumns + 2
Next y
End With
End Sub
To update the code change Sheet1 to whichever sheet you need to
formula to appear in.
Change CostColumn=1 to the correct column
number you want the formula to refer to.
Change y = 1 To 30 to
the correct columns you want the formula to appear in.
The code uses R1C1 syntax as it's easier to update a formula if you only need to deal with row & column numbers R73C2 is row 73, column 2 for example.

Resources