excel vba loop thru range and copy to single cell - excel

I am trying to do a loop with Excel VBA, I have a data range in a1:a1000, I want to loop through them and copy one by one to single cell of C1, but below code not working, any idea what went wrong?
Dim I As Integer
For I = 1 To lastrow - 1
Sheets("display").Range("w1").Value = Sheets("data").Range("c1").Offset(I, 0).Value
msgbox Sheets("data").Range("c1").Value
Next I

You're setting the value in cell "W1" instead of "C1".
Updated After Author's Clarification of Question:
Below are two ways you can loop through cells and copy/paste. Neither one is "better". I would like to emphasize that there are probably more efficient methods than these to accomplish your task, but hopefully this answer gets you a resolution.
Sub LoopExampleUsingRange()
Dim aCell As Range
For Each aCell In Range("A1:A1000").Cells
aCell.Copy Range("C1")
Next aCell
End Sub
Sub LoopExampleUsingIntegerReference()
Dim i As Integer
For i = 1 To 1000
Range("A" & i).Copy Range("C1")
'I prefer to use offset, but they both work:
'Range("A1").Offset(i - 1, 0).Copy Range("C1")
Next i
End Sub

Related

Excel, search multiple columns for cells that contain partial similar data

Wonder if someone could give me a pointer, or maybe it's already been ask then just a reference, but how can I highlight cells in an excel spreadsheet that contains multiple columns where any portion of a text matches?
Example say cell A2 has the text 'Ionized Sea Salt' and cell D5 has 'Salt'. I would like to highlight those cells because of the matching word 'Salt'.
I don't want to have to add the word I'm searching for in the formula because all the cells and columns will contain hundreds of different strings and I'm looking for matching word(s) per cell.
Thanks
Allthough you should have attempted to at least start coding something, this one is quite fun to work on so hereby my attempt :)
Sub Hightlight()
Dim MyArray() As String
Dim X As Long
Dim C As Range
ActiveSheet.UsedRange.Cells.Interior.Pattern = xlNone 'Clear the hightlighted cells
MyArray() = Split(ActiveCell.Value, " ") 'Get the activecell and split it in array
For X = LBound(MyArray) To UBound(MyArray) 'Loop through your array using .findnext
With ActiveSheet.UsedRange
Set C = .Find(MyArray(X), lookat:=xlPart)
If Not C Is Nothing Then
firstaddress = C.Address
Do
C.Interior.ColorIndex = 37 'color found matched cells
Set C = .FindNext(C)
If C Is Nothing Then
GoTo DoneFinding
End If
Loop While C.Address <> firstaddress
End If
DoneFinding:
End With
Next X
End Sub
The biggest plus of this approach is it wont have to go through thousands of cells, so therefor should be relative fast.
I am sure some true expert can cleanup this code even better :)
Input:
Output:
So.... add a button to your sheet, assign the macro, select a cell, hit the button...
Untested but should work:
Private Sub reset_highlighting()
ActiveSheet.Cells.Interior.Color = xlNone
End Sub
Private Sub highlight_d5()
' Call reset_highlighting < remove comment if you dont want to store prev results
Dim lr as Long
lr = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
Dim search_range as Range: Set search_range = Range(Cells(1,1), Cells(lr, 1))
Dim search_value = Range("D5").Value2
For each cell in search_range
If (InStr(Trim(LCase(cell.Value2)), Trim(LCase(search_value))) != 0) Then
cell.Interior.Color = vbYellow
End If
Next cell
End Sub
Note, you should replace ActiveSheet with Sheets("YourSheetName")
and also might want to adjust your range to fir the criteria
accordingly
PS: Post your efforts of you trying to solve the question in the future. Questions where no attempt was made generally tend to get downvoted here, I only made an exception given you're new here (and I have a good mood today)

Excel VBA loop through column and insert rows based on cell value

Hello!
I am trying to build a code that loops through each cell in range C8:C3276 and inserts a new row below if the cell value is "Total".
Here is the code i have so far:
Sub Create_new_rows()
Dim rng As Range
Dim cell As Range
Set rng = Range("C8:C3276")
For Each cell In rng
If ActiveCell.Value = "Total" Then
ActiveCell.Offset(1, 0).Activate
ActiveCell.EntireRow.Insert
End If
Next cell
End Sub
Nothing happens when i execute the code. I assume the code is built incorrectly as the macro runs (i get no error message), but without doing anything.
Any help is greatly appreciated! :)
Two problems I think. 1) You should loop backwards as otherwise you will skip rows as you are adding more rows, and 2) in your loop you should have referred to cell rather than the ActiveCell which is never set.
Sub Create_new_rows()
Dim rng As Range, r As Long
Set rng = Range("C8:C3276")
For r = rng.Count To 1 Step -1
If rng(r).Value = "Total" Then
rng(r + 1).EntireRow.Insert
End If
Next r
End Sub

VBA Macro to run on a specific worksheet

I am looking to have a macro to run for a specific worksheet only. The purpose of the macro would be to look for a specified range and find negative values and if there is any to extract the whole row into a new worksheet and at the same time transform those negatives to positives. I came up with some but i know for sure that this is totally wrong...missing a lot of stuff. Still trying to learn, new to this vba stuff. Thanks in advance for any help that you can provide. fyi ntp stands for negativestopositives. Not sure if that will help, just thought i can write all the details to my small "code"
Sub ntp()
Dim ws As Worksheet
If ws.Name <> "originalNeg" Then
For Each Cell In Range("I2:I1048576")
If Cell.Value < 0 Then
Cell.Value = Abs(Cell.Value)
End If
Next Cell
End Sub
Sub ntp()
Dim ws As Worksheet
Dim cel As Range
With Activeworkbook.Worksheets("originalNeg")
For Each cel In .Range("I2:I" & .Range("I" & Rows.Count).End(xlUp).row)
If cel.Value < 0 Then cel.Value = Abs(cel.Value)
Next cel
End With
End Sub
This uses the worksheet, and note the . before Range() which links the range to that specific sheet.
Also, only rarely would you want to use all cells in a column. I used the .End(xlUp).Row to get the last used row in Column I for you to loop through.
Set ws = ThisWorkbook.Worksheets("originalNeg")
instead of the if on the name.

Use VBA to Update Conditional Formatting Ranges?

I'm trying to update the conditional formatting range for about 30 rows of data on a worksheet. Every month I update the data and I want to run a macro to adjust the ranges to incorporate the new month. I've already done this for my charts by updating the end of the series ranges by looping through the ChartObjects and SeriesCollection.
To do this on conditional formatting, everything I've found requires hardcoding a range (either a cell reference or a named range), e.g.:
With Worksheets(1).Range("e1:e10").FormatConditions(1)
I'd prefer to just loop through the collection of conditional formatting for the worksheet, but I can't find any evidence of this collection existing in the Excel VBA Object Model. Am I missing something here?
This is a little convoluted since there isn't really any great way to loop through formatconditions in a sheet. But, you can loop through specialcells and then loop through their formatconditions and dig in from there:
Sub test()
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Dim rngCell As Range
Dim lng As Long
For Each rngCell In ws.Cells.SpecialCells(xlCellTypeAllFormatConditions).Cells
For lng = 1 To rngCell.FormatConditions.Count
On Error Resume Next
Debug.Print rngCell.FormatConditions(lng).Formula1, rngCell.FormatConditions(lng).AppliesTo.Address
Next lng
Next rngCell
End Sub
I poached the specialcells() idea from Dick Kusleika's excellent post on this very subject at dailydoseofexcel.com blog.
You can use code as below: Here Based on condition Highlighted the row in yellow color. You can use your formatting
LastColumnARows = WB_Source.Sheets(SheetName.Name).range("A" & Rows.Count).End(xlUp).Row
With WB_Source.Sheets(SheetName.Name)
For i = 2 To LastColumnARows
If .range("A" & i).Value > [Condition] Then
With .range("A" & i & ":E" & i)
.Interior.Color = vbYellow
.Font.Color = vbBlack
End With
End If
Next i
End With

How to concatenate text from a column into a new column? VBA Excel

I'm new to vba programming and I would like to work on a function to fix salutations in an excel file.
To start, I would just like to append a Dear " to a name in the first column, and put this value in the next column, so that I would end up with the name in the first column and "Dear name" in the next column.
The function I have so far, is putting "Dear " in the next column, but it is not appending that to the text in the first column. Could someone help me correct my code?
Sub letterSalutationFixer()
Dim letterSalutationColumn As Range
Set letterSalutationColumn = Columns(1)
For Each Cell In letterSalutationColumn
Cell.Offset(, 1).Value = "Dear " & Cell.Text
Next
End Sub
PS. I do realise that I don't necessarily need to do this programmatically since it doesn't take that long to do with the functions already available, but I eventually want to expand this to fix other data with more complexity - and just thought I could start with something simple.
Many thanks in advance!
The reason it's blank is that Cell is equivalent to the whole column. You're close though. If you did...
For Each Cell In letterSalutationColumn.Cells
..l it would cycle through each cell.
However, the way it's written, it would cycle through each cell in the whole column, which could crash Excel, or at least slow things way down.
Here's a reworked version of what you're trying to do. It only acts on the cells in column A with content:
Sub Salutation()
Dim ws As Excel.Worksheet
Dim LastRow As Long
Dim NameRange As Excel.Range
Dim cell As Excel.Range
Set ws = ActiveSheet
With ws
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set NameRange = .Range("A2:A" & LastRow)
For Each cell In NameRange
cell.Offset(, 1) = "Dear " & cell.Text
Next cell
End With
End Sub
It also declares all variables, something you want to get in the habit of doing. Do a search on Option Explicit to learn how to force yourself to.
It also uses a With statement to fully qualify Object references, so that instead of just referring to Column(1) or Range(something) you're specifying that it's in ws, which has been set to the ActiveSheet.
Another way is the VBA alternative of
Using a formula in column B that runs the concatenation against the used part of column A (ie in B1 ="Dear " &A1 etc)
The formula then is copied over itself as a value to remove the formula
code
Sub QuickCon()
Dim rng1 As Range
Set rng1 = Range([a1], Cells(Rows.Count, "A").End(xlUp))
With rng1.Offset(0, 1)
.FormulaR1C1 = "=""Dear "" &RC[-1]"
.Value = .Value
End With
End Sub

Resources