How to skip through selected cells in EXCEL, using VBA, - vba

I have a VBA macro which selects several cells based on if it contains conditional formatting. These cells won't all be in the same place on each sheet.
What I am looking for is a command to skip the activecell to the next cell in the range.
The same as pressing TAB on a highlighted range
At the moment I am using sendkeys, as below, however this is messy, and keeps adding Tab spaces in the next line of the vba code (hence the "____Loop")
ActiveCell.SpecialCells(xlCellTypeAllFormatConditions).Select
Do Until Recount = Count
Recount = Recount + 1
Application.SendKeys "{TAB}", True
Loop
Any advice would be appreciated

Here's how you can loop over the range:
Dim rng As Range, c As Range
Set rng = ActiveSheet.UsedRange.SpecialCells(xlCellTypeAllFormatConditions)
For Each c In rng
c.Select
Next c
It's not clear what the aim of your code is though. What are Count and Recount?

Get a list of selected cells and loop through them
Sub loopThroughCells()
Dim r as Range
Set r = Application.Selection
For i = 0 to r.length
MsgBox(r.value)
Next i
End Sub
Suppose three cells with values 1, 2 and 3 are selected. On running the above macro, you will get message boxes with the values 1, 2 and 3 respectively.

If you only need the command for the tab button, just use the .offset(#of rows you want to offset, #of columns you want to offset). So once you know how to locate the cells you need, which you seem to already have, then you can just put.offset(0,1) to move one cell to the right.

Related

Trying to loop non-contiguous rows in a range

I am trying to write something that will loop through a range of non-contiguous rows in a table, and change column data in each row ... for example, ClearContents. The range will be dynamic, and the rows I want to loop through will all be "Selected."
I tried the following, but it stopped after the first row. I am pretty sure the problem is that the next row is non-contiguous to the first row:
For Each b In a.Rows
mainTasks.DataBodyRange(Range("mainTasks[Status]").Column).ClearContents
Next b
Then I had the bright idea to write something that works only the "selected" column cells. I tried using If ... .Value = Selected and that didn't work.
Am I trying to do something that Excel 2016 VBA can't do? That is, loop through non-contiguous rows in a range? I've been researching and tried several other things that don't work. Can you tell me if I am going down the wrong rabbit hole?
You don't have any variables in your loop.
It will just the clear the one column repeatedly in the loop. You need to somehow reference b in the loop to have a different outcome in each loop.
I tried to simplfy your code in the comments for testing purpose, but the following code should help,
Dim x As Integer
Dim myrange As Range
For x = 1 To 30
If (mainTasks.Cells(x, 2) = "completed" Or mainTasks.Cells(x, 2) = "Dismissed") And mainTasks.Cells(x, 3) <> "" Then
If myrange Is Nothing Then
Set myrange = mainTasks.Cells(x, 2)
Else
Set myrange = Union(myrange, mainTasks.Cells(x, 2))
End If
End If
Next x
myrange.ClearContents
I tried it out and it works Ok given the way I set it up. Hope it helps!
You will also have to add the code to copy the data, I am clearing the contents in this one, given that was your original question
This works too (i think)
Dim selectedRange As Range
Set selectedRange = Application.Selection
For Each Row In selectedRange.Rows
Debug.Print Row.Address
Next Row

Excel visiual basic: increment trouble

I am working on a code that, upon each click it'll add a number to a list, that number is copied from one sheet and is pasted on another workbook. The problem i am running into is the increment coding. I've tried { activecell = activecell + 1 } but it is adding the numbers in a descending order i.e. 7,6,5,4 and etc.enter image description here
`Sub FILER()
workbooks.open("LOG")
Activeworkbooks.windows(1)visible=false
range("A3").activate
For Each Cell In Worksheets("LOG1").range("A3:A10")
If Cell.value > 0
ActiveCell.offset(1,0).select
ElseIf Cell.Value= 0 then
activeCell.offset(1) = ActiveCell + 1
End IF
Next
End Sub
You go through the cells within a range, no need to select cells explicitly. Avoid using .Activate and .Select. You only increment the cell values if the cell value is 0.
-> clean up and shorten that code and post it into your question.

Excel VBA deleting certain rows with certain conditions

I found a code online which works but I am failing to change it for my purpose. Each entry in my spreadsheet contains different formulas as well as an Iferror function with the aim of making cells with error messages appear as blank. For example lets say a cell E3 is dependent on cell F3 with a certain formula (for clarification lets say F3/2.5). It is obvious if there is no entry in cell F3 then an error message would display in cell E3. For this reason, I use the IFERROR function to display the cell as blank. The difficulty arises when I want to delete blank rows after a click on the macro button. However, since that cell does have an entry (a formula which in turn returns an error message), that cell does not delete. Also I need to run this code over 3 different selection ranges. Please can someone help! The code I found was from a different thread on this forum and is:
`sub foo()
dim r As Range, rows As Long, i As Long
Set r = ActiveSheet.Range("A1:Z50")
rows = r.rows.Count
For i = rows To 1 Step (-1)
If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
Next
End Sub`
Thanks Alot!
EDIT: If statement added to the autofilter as it was deleting a row when there were no blanks
You will want to set up a column in the spreadsheet with the following sumproduct:
=SUMPRODUCT((LEN(A1:F1)>0)*1)
This is calculating how many cells' values have a length more than 0 hence are not blank, you will need to adjust cell references accordingly as I tested on a small sample of fake data.
Following this you can just loop:
For i = rows To 1 Step (-1)
If Cells(i,"G") = 0 Then r.rows(i).Delete 'My formula is in column "G"
Next
Or set up an auto-filter and delete entire rows of the visible cells:
Dim lrow As Integer
If Not WorksheetFunction.CountIf(Range("G:G"), "0") = 0 Then
Range("A1:G1").AutoFilter
Range("A1:G1").AutoFilter Field:=7, Criteria1:="0"
lrow = Cells(rows.Count, 7).End(xlUp).Row + 1
Range("G2:G" & lrow).SpecialCells(xlCellTypeVisible).EntireRow.Delete
Range("A1:G1").AutoFilter
End If
The only problem with using a leading column to calculate for this is if you have a lot of data coming and going as you will need to replenish the formula, though you could use auto complete in the code i guess.

How do I add “+1” to all cells in a user selected range?

I need to have the user select a range of cells with their mouse and then run a macro to add +1 to that selected range. The range will often be different every time, so it cannot be defined.
Here's what I have so far, it just works on a single active cell, I cannot get it to work on a range selection, because I do not know what to define or function to utilize.
My code Follows:
Sub Add()
ActiveCell.Value = ActiveCell.Value + 1
End Sub
The below code uses the built-in Paste Special Add feature to add 1 to every cell in the selected range.
Sub AddOneToSelection()
Dim rBlank As Range
If TypeName(Selection) = "Range" Then
'Put a '1' in an unused cell and copy it
Set rBlank = ActiveSheet.Cells.SpecialCells(xlLastCell).Offset(1, 0)
rBlank.Value = 1
rBlank.Copy
'Paste Special Add over the selection
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlAdd
'Get rid of the copied cell
rBlank.ClearContents
End If
End Sub
The benefit of this over looping is that Paste Special Add treats formulas and values differently and you don't have to code that part yourself.
The downside is you increase your UsedRange by one row, if that matters to you.
This should work for you:
Dim r, c As Range
Set r = Selection
For Each c In r
c.Value = "+1"
Next
This assumes that your cell formats will display "+1" instead of "1". You can set the format of your cells to "Text".

VBA Go to last empty row

I have a project on excel macro, I need to highlight the next last row that has an empty value. example cell A1:A100 have data and the next cell is A101 is empty.
when user click a button it should highlight the cell A101...
If you are certain that you only need column A, then you can use an End function in VBA to get that result.
If all the cells A1:A100 are filled, then to select the next empty cell use:
Range("A1").End(xlDown).Offset(1, 0).Select
Here, End(xlDown) is the equivalent of selecting A1 and pressing Ctrl + Down Arrow.
If there are blank cells in A1:A100, then you need to start at the bottom and work your way up. You can do this by combining the use of Rows.Count and End(xlUp), like so:
Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select
Going on even further, this can be generalized to selecting a range of cells, starting at a point of your choice (not just in column A). In the following code, assume you have values in cells C10:C100, with blank cells interspersed in between. You wish to select all the cells C10:C100, not knowing that the column ends at row 100, starting by manually selecting C10.
Range(Selection, Cells(Rows.Count, Selection.Column).End(xlUp)).Select
The above line is perhaps one of the more important lines to know as a VBA programmer, as it allows you to dynamically select ranges based on very few criteria, and not be bothered with blank cells in the middle.
try this:
Sub test()
With Application.WorksheetFunction
Cells(.CountA(Columns("A:A")) + 1, 1).Select
End With
End Sub
Hope this works for you.
This does it:
Do
c = c + 1
Loop While Cells(c, "A").Value <> ""
'prints the last empty row
Debug.Print c