insert a column to the left of cell vba - excel

I need to loop through a header row and insert an entire column to the left based on certain conditions.
Sub InsertCol()
Dim i As Integer
For i = 1 To 20
If i Mod 2 = 0 Then
Cells(1, i).Columns.Insert ' this only inserts a cell..need an entire column
End If
Next i
End Sub

You need to use Columns(i).Insert
Sub InsertCol()
Dim i As Integer
For i = 1 To 20
If i Mod 2 = 0 Then
Columns(i).Insert
End If
Next i
End Sub
Note that you may want to step backwards through this loop since you're inserting columns:
Sub InsertCol()
Dim i As Integer
For i = 20 To 1 Step -1
If i Mod 2 = 0 Then
Columns(i).Insert
End If
Next i
End Sub

You're probably looking for something more like
Columns("B:B").Insert Shift:=xlToLeft
This will insert a column to the left of the specified range ("B:B") in my example.
You also don't need to refer to the full range, you can just refer to i so.
Columns(i).Insert Shift:=xlToLeft

Related

Excel Loop Column A action column B

I'm currently looking for a code to improve my Dashboard. Actually, I need to know how to use a loop in a column X who will affect a column Y (cell on the same line).
To give you an example:
Column A: I have all Production Order (no empty cell)
Column B: Cost of goods Sold (Sometimes blank but doesn't matter)
I actually pull information from SAP so my Column B is not in "Currency".
The action should be:
If A+i is not empty, then value of B+i becomes "Currency".
It's also for me to get a "generic" code that I could use with other things.
This is my current code...
Sub LoopTest()
' Select cell A2, *first line of data*.
Range("A2").Select
' Set Do loop to stop when an empty cell is reached.
Do Until IsEmpty(ActiveCell)
ActiveCell.Offset(0, 1).Style = "Currency"
ActiveCell.Offset(1, 0).Select
Loop
End Sub
Another example, getting Last Row, in case your data contains any blank rows.
Sub UpdateColumns()
Dim wks As Worksheet
Dim lastRow As Long
Dim r As Long
Set wks = ActiveSheet
lastRow = ActiveSheet.Cells.SpecialCells(xlLastCell).Row
For r = 2 To lastRow
If wks.Cells(r, 1) <> "" Then
wks.Cells(r, 2).NumberFormat = "$#,##0.00"
End If
Next r
End Sub
I can see I was a little slower than the others, but if you want some more inspiration, heer is a super simple solution (as in easy to understand as well)
Sub FormatAsCurrency()
'Dim and set row counter
Dim r As Long
r = 1
'Loop all rows, until "A" is blank
Do While (Cells(r, "A").Value <> "")
'Format as currency, if not blank'
If (Cells(r, "B").Value <> "") Then
Cells(r, "B").Style = "Currency"
End If
'Increment row
r = r + 1
Loop
End Sub
Try the following:
Sub calcColumnB()
Dim strLength As Integer
Dim i As Long
For i = 1 To Rows.Count
columnAContents = Cells(i, 1).Value
strLength = Len(columnAContents)
If strLength > 0 Then
Cells(i, 2).NumberFormat = "$#,##0.00"
End If
Next i
End Sub
Explanation--
What the above code does is for each cell in Column B, so long as content in column A is not empty, it sets the format to a currency with 2 decimal places
EDIT:
Did not need to loop
Here's a really simply one, that I tried to comment - but the formatting got messed up. It simply reads column 1 (A) for content. If column 1 (A) is not empty it updates column 2 (B) as a currency. Changing active cells makes VBA more complicated than it needs to be (in my opinion)
Sub LoopTest()
Dim row As Integer
row = 1
While Not IsEmpty(Cells(row, 1))
Cells(row, 2).Style = "Currency"
row = row + 1
Wend
End Sub

change values of a column

I need to change values of a column in EXCEL 2010 on Win 7.
This the macro. But, it only works for one cell even though I selected a column with 1000 tows.
Sub Change0to1()
SelectedRange = Selection.Rows.Count
ActiveCell.Select
For i = 1 To SelectedRange
If ActiveCell.Value = 0 Then
ActiveCell.Value = 1
End If
Next i
End Sub
Any help would be apprecaited.
Thanks
I think you want
Sub Change0to1()
For i = 1 To Selection.Cells.Count
If Selection(i).Value = 0 Then
Selection(i).Value = 1
End If
Next i
End Sub
This iterates through all the cells in the selection so it doesn't matter whether they are in a row and it doesn't matter which of the selected cells is the active cell.
Try this one:
Sub Change0to1()
Dim c As Range
For Each c In Selection
If c.Value = 0 Then c.Value = 1
Next c
End Sub
Note, that For Each loop is faster than For i = ..

How to delete a row if it contains a string?

I have only one column of data. I need to write a macro that would go through all the values and delete all rows that contain the word "paper".
A B
1 678
2 paper
3 3
4 09
5 89
6 paper
The problem is that the number of rows is not fixed. Sheets may have different number of rows.
Here is another simple macro that will remove all rows with non-numeric values in column A (besides row 1).
Sub DeleteRowsWithStringsInColumnA()
Dim i As Long
With ActiveSheet '<~~ Or whatever sheet you may want to use the code for
For i = .Cells(.Cells(.Rows.Count, 1).End(xlUp).Row, 1).Row To 2 Step -1 '<~~ To row 2 keeps the header
If IsNumeric(.Cells(i, 1).Value) = False Then .Cells(i, 1).EntireRow.Delete
Next i
End With
End Sub
If you're confident that the rows in question would always contain "paper" specifically and never any other string, you should match based on the value paper rather than it being a string. This is because, particularly in Excel, sometimes you may have numbers stored as strings without realizing it--and you don't want to delete those rows.
Sub DeleteRowsWithPaper()
Dim a As Integer
a = 1
Do While Cells(a, 1) <> ""
If Cells(a, 1) = "paper" Then
Rows(a).Delete Shift:=xlUp
'Row counter should not be incremented if row was just deleted
Else
'Increment a for next row only if row not deleted
a = a + 1
End If
Loop
End Sub
The following is a flexible macro that allows you to input a string or number to find and delete its respective row. It is able to process 1.04 million rows of simple strings and numbers in 2.7 seconds.
Sub DeleteRows()
Dim Wsht As Worksheet
Dim LRow, Iter As Long
Dim Var As Variant
Var = InputBox("Please specify value to find and delete.")
Set Wsht = ThisWorkbook.ActiveSheet
LRow = Wsht.Cells(Rows.Count, 1).End(xlUp).Row
StartTime = Timer
Application.ScreenUpdating = False
With Wsht
For Iter = LRow To 1 Step -1
If InStr(.Cells(Iter, 1), Var) > 0 Then
.Cells(Iter, 1).EntireRow.Delete
End If
Next Iter
End With
Application.ScreenUpdating = True
Debug.Print Timer - StartTime
End Sub

Excel odd rows give value

I am trying to assign a value to all the odd cells in a particular column/range. So far I have the following code taken from another question, but it isnt working:
Sub changeClass()
Dim r As Range
Set r = Range("B16").End(xlDown) 'set the range the data resides in
For i = 1 To r.Rows.Count 'merge step
If i Mod 2 = 1 Then 'this checkes to see if i is odd
r.Cells.Value = "value"
End If
Else
r.Cells.Value = "value2"
Next i
End Sub
Basically I need it to add in a value for every cell in the B column from cell 16 down to the last cell i nthe column which has data in. On the even rows the value will be one thing, on the odd it will be another.
Many thanks!
Sub changeClass()
Dim r As Range
Dim i As Integer
For Each r In Range("B16:B24") 'Change this range
i = r.Row
If i Mod 2 = 1 Then 'this checks to see if i is odd
r.Cells.Value = "ODD"
Else
r.Cells.Value = "EVEN"
End If
Next r
End Sub
Try this out, I believe it is not working, because you are not acessing each individual cell inside your loop. In the following macro i use 'rng' to represent the entire range of cells, and 'r' to represent a single cell in each increment of the loop.
Sub changeClass()
Dim rng As Range
Dim r As Range
Set rng = Range(Cells(16,2),Cells(16,2).End(xlDown))
For i = 1 To rng.Rows.Count
Set r = rng.Cells(i)
If i Mod 2 = 1 Then ' You may want to test if it is odd based on the row number (depends on your problem...)
r.Value = "Odd Value"
Else
r.Value = "Even Value"
End If
Next i
End Sub
you've messed up your if statement, don't close it off before else close it only once you are completely done with it! ;) here:
Sub changeClass()
Dim r As Range
Set r = Range("B16").End(xlDown) 'set the range the data resides in
For i = 1 To r.Rows.Count 'merge step
If i Mod 2 = 1 Then 'this checkes to see if i is odd
r.Cells.Value = "value"
Else
r.Cells.Value = "value2"
End if
Next i
End Sub
You don't need a loop for this:
Sub OddRowAlert()
With Range("B16:B100")
.Formula = "=IF((MOD(ROW(B16),2)),""Odd"",""Even"")"
.Formula = .Value
End With
End Sub
Just replace odd and even in the formula with what you want

Visual Basic Excel Macro

I want to have a little Macro in excel. The Macro should take a double number from A1 and multiply this number by 5 and return it back into A1 but i always get error messages etc.
My code up to now:
Function multiply()
Dim a As Long
For a = 1 To 65563
cell(a,3) = cell(a,3).Value * 5
next a
End Function
I have not worked with VBA before.
That does what you ask, but it's a sub as you can't edit worksheet values using a function
Public Sub multiply()
On Error GoTo err
Dim val As Long
val = ActiveSheet.Cells(1, 1).Value
ActiveSheet.Cells(1, 1).Value = val * 5
Exit Sub
err:
End Sub
you dont need to use function just use these subs:
bellow you can multiplay all of *column A * values:
Sub example()
For a = 1 To 65563
Cells(a, 1).Value = Cells(a, 1).Value * 5
Next a
End Sub
considering 65563 CELLS isn't a good idea, i suggest you to use the sub bellow to count rows and reduce memory usage.
Sub example2()
Dim countrows As Long
countrows = Range("A" & Rows.Count).End(xlUp).Row
For a = 1 To countrows
Cells(a, 1).Value = Cells(a, 1).Value * 5
Next a
End Sub
You don't actually need a macro for this - although if you do want to use VBA you can avoid time consuming loops altogether
1 Manual Method using Paste Special - Multiply
from walkenbach
To increase a range of values by 5 times:
Enter 5 into any blank cell.
Select the cell and choose Edit, Copy.
Select the range of values (Column A in your example) and choose Edit, Paste Special.
Choose the Multiply option and click OK.
Delete the cell that contains the 5
2 Code using Paste Special - Multiply
Using Zack Barresse's code from vbax - with minor amendments
This code updates the selected range with a user-entered multiplier
Sub psMultiply()
' http://www.vbaexpress.com/kb/getarticle.php?kb_id=47
Dim y As Long 'The multiplier value, user-defined
Dim x As Range 'Just a blank cell for variable
Dim z As Range 'Selection to work with
Set z = Selection
y = Application.InputBox("Enter selection multiplier:", _
Title:="Selection multiplier", Default:=10, Type:=1)
Set x = Cells(Rows.Count, "A").End(xlUp).Offset(1)
If y = 0 Then Exit Sub 'Cancel button will = 0, hence cancel
If x <> "" Then
Exit Sub
Else: x.Value = y
x.Copy
z.PasteSpecial Paste:=xlPasteAll, Operation:=xlMultiply
Application.CutCopyMode = False 'Kill copy mode
End If
x.ClearContents 'Back to normal
End Sub
Why not make it a little more generic by only multiplying the numbers you select:
Sub MultiplyByFive()
Dim cl As Range
For Each cl In Selection
cl = cl * 5
Next cl
End Sub
This way you avoid the 65536 hard coding.

Resources