I have data in column D.
There is a header in column D1 and numeric values in D2 downward. I would like to select all numeric values in column D (the number of values is unknown) and multiply them by -1 (replacing the current values in column D). How would I do this through VBA code?
If I could use formulas in Excel I would simply drag the formula D2*-1 downward; however, I need the VBA equivalent.
The following works almost instantaneously when tested with 100,000 random values:
Sub MultColDbyOne()
Dim i As Long, n As Long, A As Variant
n = Cells(Rows.Count, "D").End(xlUp).Row
A = Range(Cells(2, "D"), Cells(n, "D")).Value
For i = LBound(A) To UBound(A)
A(i, 1) = -A(i, 1)
Next i
Range(Cells(2, "D"), Cells(n, "D")).Value = A
End Sub
The sub works by first determining the last row with data in column D, then transferring it to a VBA array (which is, somewhat annoyingly, a 2-dimensional array with only 1 column), looping through that array replacing each number in it by its negative, then transferring it back. This Range to array then back to Range strategy is fairly common (and fairly efficient) in VBA.
Just for curiosity I wanted to employ selecting special cells (numbers) feature of Excel. I created another function and tested the speed against the function created by #John Coleman.
If column D contains 10,000 values, #John Coleman's function is faster.
If column D contains 1,000,000 values, this function is faster.
Sub ChangeSignColD()
Dim v, x As String
Application.ScreenUpdating = 0
x = Selection.Address
With Cells(1, 5)
v = .Value
.Value = -1
.Copy
Columns("D:D").SpecialCells(2, 1).PasteSpecial -4163, 4
.Value = v
End With
Range(x).Select
Application.CutCopyMode = 0
End Sub
In addition, I noticed that this function would not error if there was e.g. some text value in the column.
I like how #Zygd solve it, but i propose to use a cell for the -1 not interfering with existing working range.
Sub InvertNumericSign()
Dim LastCell As Range
Dim SignRng As Range
Set LastCell = Cells.SpecialCells(xlCellTypeLastCell)
Set SignRng = Selection
If Not LastCell = "" Then Set LastCell = LastCell(2, 2)
LastCell = -1
LastCell.Copy
SignRng.PasteSpecial Paste:=xlPasteValues, Operation:=xlMultiply
LastCell.ClearContents
End Sub
Related
i have a list of names(Column A), the numbers in columns B to F are result of a formula. I'm trying to create a FOR LOOP code that will check columns B to F, if all cells in B to F are zero then the code should ignore the current row and skip to the next row; if any of the cells in columns B to F is greater than 0, then the code should get the corresponding name in Column A.
Example: If any of the cells in B2, C2, D2, and E2 is greater than 1, then i should get the name/value of A2. if all cells in B2, C2. D2, and E2 are all zeros, then proceed to check next row and do the same thing.
here's the code i used to try to get the names that has any of the 4 column cell values greater than 1
For i = 2 To LastCalcAnalystRowIndex '//wsCalculations.Cells(Rows.Count, "CP").End(xlUp).Row
'//Get Component from cell in column "BP"
Analyst = wsCalculations.Cells(i, "CP").Value
Component = wsCalculations.Cells(i, "CN").Value
weeknumber = wsCalculations.Range("BR2").Value + 3
If wsCalculations.Cells(i, "B").Value = 0 And wsCalculations.Cells(, "C").Value = 0 _
And wsCalculations.Cells(i, "D").Value = 0 And wsCalculations.Cells(i, "E").Value = 0 _
And wsCalculations.Cells(i, "F").Value = 0 Then
Exit For
Else
wsCalculations.Cells(i, "A").Value = wsCalculations.Cells(i, "CP").Value
End If
Next
using the code above, i tried to get the names which all 4 column values are not equal to zero, but the result i get is just a copy of the original list. i highlighted the rows i want my code to skip. i also included the result i get and the result i want to get.
Below is a sample data. My original data has 54 rows. .
can anyone please tell me what im getting wrong?
There's no real need for VBA.
Note that I have used a Table with structured references. You can change it to a range with normal references if you prefer.
If you have O365, you can use a helper column and a formula.
Add a helper column which SUM's the cells in each row (and you can hide that column if necessary).
eg: G2: =SUM(Table3[#[Column2]:[Column6]])
Then, assuming the data is in a Table named Table3 use the formula:
=INDEX(FILTER(Table3,Table3[sumRow]>0),0,1)
If you have an earlier version of Excel, you can use:
I2: =IFERROR(INDEX(Table3[Column1],AGGREGATE(15,6,1/(Table3[sumRow]>0)*ROW(Table3)-ROW(Table3[#Headers]),ROWS($1:1))),"")
and fill down the length of the table.
Not the solution but could shorten your initial code
Why not create a hidden column* that does an =SUM of the entire row
Then get the value from that
instead of using code to get the value of each 5 cells then adding it up.
edit: changed the 'hidden cell' to 'hidden column' :P
Try
Sub test()
Dim rngDB As Range
Dim rng As Range, rngSum As Range
Dim wsCalculations As Worksheet
Dim vR() As Variant
Dim n As Long
Set wsCalculations = ActiveSheet
With wsCalculations
Set rngDB = .Range("a2", .Range("a" & Rows.Count).End(xlUp))
End With
For Each rng In rngDB
Set rngSum = rng.Offset(, 1).Resize(1, 5)
If WorksheetFunction.Sum(rngSum) > 0 Then
n = n + 1
ReDim Preserve vR(1 To n)
vR(n) = rng
End If
Next rng
With wsCalculations
If n Then
.Range("h2").Resize(n) = WorksheetFunction.Transpose(vR)
End If
End With
End Sub
can anyone please tell me what im getting wrong?
actually your shown code isn't consistent with your wording, so it's impossibile to tell all that's wrong
but for sure that Exit For is a logical error, since it actually gets you out of the loop when it first meets five zeros
so as far as this logical error is concerned, you should change that piece fo code to the following:
With wsCalculations
For i = 2 To .Cells(.Rows.Count, "A").End(xlUp).Row
If WorksheetFunction.CountIf(.Cells(i, 2).Resize(, 5), 0) < 5 Then ' when a row is eligible for math
' do your math
End If
Next
End With
where I used WorksheetFunction.CountIf() function that enables you to deal with different conditions since your wording wasn't clear about this item, too ("greater than 0", "all cells...are zero", "greater than 1")
I need to convert the column with Dates, formatted in Date formats into text format and if possible in reverse.
I can apply worksheet function TEXT, fill down by copy pasting or double clicking and then copy/cut the helper column and paste as value in the original column and record the macro, but is there any way to do so without selecting/activating, autofilling, using helper columns,(like "H" and "I") in this example? Will any vba function in place of worksheet function result in more efficiency?
Sub DateFormatToText()
Range("H2").Select
ActiveCell.FormulaR1C1 = "=TEXT(RC[-1],""dd/mm/yyyy"")"
Range("H2").Select
Selection.AutoFill Destination:=Range("H2:H20")
End Sub
Browsing through, I came to know those are not optimal codes.
You can try like below:
Range("H2:H" & Range("G" & Rows.Count).End(xlUp).Row).Formula = "=TEXT(G2,""dd/mm/yyyy"")"
With no helper columns, no worksheet formulas
To change the date entries in the same column, something like:
Option Explicit
Sub colGtoText()
Dim v, i As Long, r As Range, ws As Worksheet
'define the working area of Column G entries
Set ws = ThisWorkbook.Worksheets("sheet1")
With ws
Set r = .Range(.Cells(1, "G"), .Cells(.Rows.Count, "G").End(xlUp))
v = r.Value 'read into vba array for faster processing
End With
With r
.NumberFormat = "#" 'change to text format
'process each entry to the appropriately formatted text string
For i = 1 To UBound(v)
If IsDate(v(i, 1)) Then v(i, 1) = Format(v(i, 1), "mm/dd/yyyy")
Next i
'write results back to the range from the vba array
.Value = v
End With
End Sub
=TEXT(G2,"dd-mm-yyyy")
used - operation either using Replace function
I'm really new to VBA and have been working section by section on a number of pieces of code to format a worksheet (I've been doing it piece by piece so that I understand how each works, and using a final macro to Call all the macros into one long process).
Issue is sometimes the worksheets I work with are not exported with columns in the same order from month to month (out of my control), thus to autosum a particular column I have to Find the column header, then autosum that column, but this makes the column letter(or number) completely variable. I know how to work with rows as variables, but I'm stuck on column. I've been scouring forums to try and find a concise explanation, but to no avail, yet.
This code DOES work for column Y specifically, but I'm trying to figure out how to get it to use a variable for the column.
For example, I'm using a separate Macro called "FindInvoiceColumn" to select the 1st cell in the column that contains the string "invoice_amount", then I'd like to use something like I wrote below to set "ColumnAddress" as the column value of that cell. As far as I know .Column returns the column number, which is fine, but I'm assuming I'd have to use with Cells() instead of Range(), I just don't know how to get here.
(Part of the code also shows Adding the word "Total" to the left of the cell containing the autosum value, and making both bold).
Here's what I have so far:
Dim Rng As Range
Dim c As Range
Set Rng = Range("Y" & rows.Count).End(xlUp).Offset(1, 0)
Set c = Range("Y1").End(xlDown).Offset(1, 0)
c.Formula = "=SUM(" & Rng.Address(False, False) & ")"
'Selects next empty row of column X to add "Total" label for sum of column Y'
Range("X" & Cells.rows.Count).End(xlUp).Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "Total"
'Bolds Total and the Sum of invoices'
Range("X" & Cells.rows.Count).End(xlUp).Select
Selection.Font.Bold = True
Range("Y" & Cells.rows.Count).End(xlUp).Select
Selection.Font.Bold = True```
'The below is what I'd like to use to find the dynamic value of the column.'
'Finds cell in row 1 that contains column header "invoice_amount" and selects it'
Call FindInvoiceColumn
'Dim ColumnAddress As Integer
ColumnAddress = ActiveCell.Column
You can use .Address to get a column reference, such that:
Sub test()
Dim varCol As String
varCol = Columns(ActiveCell.Column).Address
Debug.Print varCol 'OUTPUTS $A:$A when I had cells(1,1) selected
End Sub
In the above example, I chose a single cell to A) find it's column reference, via .Column, and B) found the .address of said column.
You could also perform the sum on a defined range using .cells() notation, rather than .range() notation.
Sub test2()
Dim rng As Range
Set rng = Range(Cells(1, 1), Cells(2, 1))
Cells(3, 1).Formula = "=sum(" & rng.Address & ")"
End Sub
The above code ouputs:
Specific to using the .cells() notation, you can make your column reference a variable, e.g.:
dim r as long, c as long
r = 1
c = 4
debug.print cells(r,c).address `should output $D$1 (untested)
You can choose r or c to fit your needs.
And as always... avoid select/activate where possible!!!
Edit
Adding use of last row via code since comments are terrible:
dim col as long
col = 25 'Y
With sheets("name")
dim lastRow as long
lastRow = .cells(.rows.count,col).end(xlup).row
Dim rng As Range
Set rng = .Range(.Cells(1, 1), .Cells(lastRow, col))
end with
This is exactly why I mentioned the specifics abotu the notation after that section (use of r and c as variables).
I've used this code to set a column number if your header is in a variable position
Dim F As Object
ColumnAddress = 0
With ActiveSheet.Rows(1)
Set F = .Find(What:="invoice_amount", LookAt:=xlWhole)
If F Is Nothing Then
MsgBox "This is not a proper file"
' other code
Else
ColumnAddress = F.Column
End If
End With
You would then use Cells() in place of range to do further work with the result of ColumnAddress. Also, ColumnAddress should dim as Long, to be accurate.
I have 2 columns in my excel file, and I want to get the MIN/Max/Average of the price in the second row based of the information in the first column. i cannot use the normal function as there is 200,000 rows in my workbook.
I have done this before with different data that used the date in the first column now I wish to change it as i am not using date. I am getting errors in the fist if statement.
Sub Button1_Click()
Dim Rng As Range, Dn As Range, n As Long, c As Long, K As Variant
Set Rng = Range(Range("A2"), Range("A" & Rows.Count).End(xlUp))
With CreateObject("scripting.dictionary")
.CompareMode = vbTextCompare
Application.ScreenUpdating = False
For Each Dn In Rng
If Not .Exists(DateValue(Dn.Value)) Then
.Add DateValue(Dn.Value), Dn.Offset(, 1)
Else
Set .Item(DateValue(Dn.Value)) = Union(.Item(DateValue(Dn.Value)), Dn.Offset(, 1))
End If
Next
Range("E1:H1") = Array("Date", "Max", "Min", "Average")
c = 1
For Each K In .keys
c = c + 1
Cells(c, "E") = K
Cells(c, "F") = Application.Max(.Item(K))
Cells(c, "G") = Application.Min(.Item(K))
Cells(c, "H") = Application.Average(.Item(K))
Next K
End With
Application.ScreenUpdating = True
End Sub
MIN/Max/Average of the values in column 2 that relate to the values in column 1
The "normal" functions should be working properly regardless of how many rows of data you have.
For example, I just double-checked worksheet functions MIN, MAX, AVERAGE, MINIFS, MAXIFS and AVERAGEIFS calculated on a column of 200k rows and dependant on the value of another column, and I didn't have any problem (using Excel for Office 365).
Example:
"Average of Column B where Column A equals 2"
Worksheet function:
=AVERAGEIFS(B:B, A:A, 2)
VBA WorksheetFunction:
MsgBox Application.WorksheetFunction.AverageIfs(Range("B:B"), Range("A:A"), 2)
Perhaps you're using an older version of Excel?
As far as I know, all of Excel's functions/formulas will work properly up to the maximum number of rows/columns of that the version can handle (which is 1,048,576 rows by 16,384 columns since at least Excel 2007).
In Excel, I am trying to get a macro to move numbers with a "-".
I have a column E with a list of numbers
54525841-1
454152
1365466
1254566-1
1452577-1
I want a macro to move all the numbers that have a dash or hyphen at the end to column C.
So I would need E1 54525841-1 to be moved to C1.
You'll need to change "Sheet1" to the name of the sheet where your data is.
This looks through every cell (with data) in the E column and moves the value accross to the C column if it contains a dash.
Sub MoveDashes()
Dim Sheet As Worksheet
Dim Index As Long
Set Sheet = ThisWorkbook.Worksheets("Sheet1")
For Index = 1 To Sheet.Cells(Application.Rows.Count, "E").End(xlUp).Row
If InStr(1, Sheet.Cells(Index, "E"), "-") > 0 Then
Sheet.Cells(Index, "C") = Sheet.Cells(Index, "E").Value
Sheet.Cells(Index, "E").Value = ""
End If
Next
End Sub
Does it have to be a macro? How about Advanced Filter?
Your numbers are in column E. Let's assume they have a header.
E1: Number
E2: 54525841-1
E3: 454152
E4: 1365466
E5: 1254566-1
E6: 1452577-1
In a separate area of your worksheet (let's say column G) put the following criteria:
G1: Number
G2: *-*
Your advanced filter criteria would look like this:
Anything with a "-" in it will be copied to column C.
I got it to work by this:
Sub MoveDash()
x = Range("E" & Rows.Count).End(xlUp).Row
For Each Cell In Range("E2:E" & x)
If InStr(Cell, "-") <> 0 Then
Cell.Offset(, 1) = Cell
Cell.ClearContents
End If
Next Cell
end sub
You can do this without VBA, but here is an efficient way to do it using the dictionary object.
Sub MoveNumbersWithDash()
Application.ScreenUpdating = False
Dim i As Long, lastRow As Long
Dim varray As Variant
Dim dict As Object
Set dict = CreateObject("scripting.dictionary")
lastRow = Range("E" & Rows.Count).End(xlUp).Row
varray = Range("E1:E" & lastRow).Value
For i = 1 To UBound(varray, 1)
If InStr(1, varray(i, 1), "-") <> 0 Then
dict.Add i, varray(i, 1)
End If
Next
Range("C1").Resize(dict.Count).Value = _
Application.WorksheetFunction.Transpose(dict.items)
Application.ScreenUpdating = True
End Sub
How it works:
The major theme here is avoiding calls to Excel (like a for each loop). This will make the function blazing fast (especially if you have tens and thousands of rows) and more efficient. First I locate the last cell used in E then dump the entire row into a variant array in one move. Then I loop through each element, checking if it contains a "-", if it does, I add it to a dictionary object. POINT: Add the entry as the ITEM, not KEY. This makes sure that we allow for duplicates. The variable I will be unique for each entry, so I use that as the key. Then I simple dump the entire array of cells with "-" into column C.
Why Dictionary?
The dictionary object is very fast and comes with 2 really great functions: .Keys and .Items. These will return an array of all the keys or items in the dictionary, which you can use the Transpose function on to dump an entire column of values into Excel in one step. Super efficient.