Trying to loop non-contiguous rows in a range - vba

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

Related

Checking if data exists and adding it if not

I have two rows containing dates which I am trying to compare and see if they are the same. If not, I want to add the extra data (i.e. row 1 can change and so I want those changes added to row 2). Ive tried looking around and also writing my own loop but I`m getting an error.
UPDATE following the comment, i am still getting an error; "Unable to get the CountIf propety of the worksheetfunction class"
I am wondering if there are any alternatives to check if the data is present somewhere in the second row add add it if not.
I am new to vba and programming in general and any help would be appreciated.
Dim Dates As Range
Set Dates = Range("C23:O23")
Dim hisdate As Range
Set hisdate = Range("C35:O35")
For Each cell In Dates 'this is gonna first add new dates
If WorksheetFunction.CountIf(hisdate, cell) > 0 Then 'do nothing
Else
Set hisdate = Union(hisdate, cell)
End If
Next
As mentioned in the comments, WorksheetFunction.CountIf doesn't work with multi-area ranges. You could write your own countIf-function that loops over all areas (works even if the range is not a multi-area range)
Dim cell As Range
For Each cell In Dates 'this is gonna first add new dates
If MyCountIf(hisdate, cell) <= 0 Then
Set hisdate = Union(hisdate, cell)
End If
Next
Debug.Print hisdate.Address
Function MyCountIf(fullRange As Range, val As Variant)
MyCountIf = 0
Dim r As Range
For Each r In fullRange.Areas
MyCountIf = MyCountIf + WorksheetFunction.CountIf(r, val)
Next
End Function

How to skip through selected cells in EXCEL, using 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.

Finding cellindex depending on cell content in excel

Im in a bit of a hard spot at the moment, i've been searching the web for some weeks now whitout any luck. I hope some of you might have the answer however.
I want to search through a row for a cell with a specific numeric value. The row contains weeknumbers. When found i would like to be able to handle the cell like an object, or at least i need to know the coordiantes of the cell for further processing.
Furthermore, can that process be reversed. Meaning, can i get the value from say the next cell in the same row if i have the coordinates of the prior cell?
Example would be:
Search through row for the week number for this week.
Hopefully get the coordinates for the cell that contains the right number.
When i have that column, i want to find the content of the cells monday to friday for that week for every coworker
I doesnt matter if this i done by VBA or formulas.
Thanks a lot in advance.
Best regards Teambit
No need for VBA for this... you should be able to achieve it with formulae easily enough.
So, cell L3 has the formula:=ADDRESS(3,MATCH($B$1,$A$3:$N$3,0)). This will perform a MATCH on the week entered into cell $B$1 and find it in the range of weeks $A$3:$N$3. The ADDRESS function will return the cell address for where the week number is found, so $G$3 in my example.
Then the lower grid/table will display the working week for the current week. The OFFSET function is moving the cell address down 3 rows, then right 1, 2, 3, 4, or 6 rows for each day of the week. OFFSET will return a 0 for a blank, so the T function is ensuring we get a text equivalent, or blank instead of 0. I'm using INDIRECT to pass the OFFSET function the starting cell address, so it is using the value of our starting week cell ($G$3), instead of that cell ($L$1).
I've not put anything in to make this dynamic per worker, so it's always using row 3, but you can get a cell reference using ADDRESS from a VLOOKUP for a name and then plug that into the other formulae.
Check if this help u..
Sub SubOne()
Dim sh As Worksheet
Dim rw As Range
Dim iFoundIt As Range
Dim RowCount As Integer
' var to iterate trough rows
RowCount = 0
Set sh = ActiveSheet
For Each rw In sh.Rows
' iterate over all cells in first row
If sh.Cells(rw.Row, 1).Value = "ThisIsMySpecialValue" Then
' value is found, we save the cell for future options
Set iFoundIt = sh.Cells(rw.Row, 1)
Exit For
End If
RowCount = RowCount + 1
Next rw
Debug.Print (iFoundIt.Row)
Debug.Print (iFoundIt.Column)
End Sub
I know if i understand your question well, but if you have coordinates of cell and you wana e.g. next cell on left you can use something like this
Sub findWeek()
Dim targetSheet As Worksheet
Set targetSheet = Sheets("Sheet1")
Dim l As Long
Dim row As Long
row = 2
Dim myVal As String
myVal = "some name of week you looking for"
Dim resultCell As Range
With targetSheet
Do While .Cells(row, l).Value <> myVal
l = l + 1
Loop
resultCell = .Cells(row, l)
End With
End Sub
So i updated answer, try something like this. Just change sheet name, maybe row and even name which are you looking for. And in value resultCell you will have object of cell which you are looking for. And if you look at cell/range api you can get its coordinates etc...
So you can make it a function which will return range, or whatever you want... But always in value resultCell will be cell which you are looking for.
Maybe you will need to take care if week is not found ;) because this will stuck in loop, but its not that hard

IF THEN VBA MACRO - Update one column if contents of another = 100%

I have a workbook with "Results" being sheet 3, this being the worksheet I want to use.
I have tried a few formulaes to try and add a macro to do the following:
I have column G with percentages. I then have column I where I would like there to be a result saying TRUE/FALSE where the contents of G are equal to 100%. Column G is formatted to percentage with two decimals.
Some considerations: I have my first row being a Hyperlink to another sheet, then my headings, then the first row of "results". I have 457 rows, if there is a measurement of the range, perhaps it could be on A?
I keep getting this error 9 with my range and have got a bit stuck.
Thanks in advance!
Sub PartialHits1()
Dim rng As Range
Dim lastRow As Long
Dim cell As Range
With Sheet3
lastRow = .Range("G" & .Rows.Count).End(xlUp).Row
Set rng = .Range("G1:G" & lastRow)
For Each cell In rng
If cell.Value = 100
Then
cell.Range("I1:I1").Value = 100
End If
Next
End With
End Sub
(I have hacked this a bit, just was trying to get it to set as 100 instead of the TRUE/FALSE Also was playing around near the Sheet 3 part as I got errors.)
RangeVariable.Range can refer only to a cell within RangeVariable, so you can't refer to column I in this way. Try: .Range("I"&cell.row)=100.
Also your criteria is probably wrong, if you have 100% in a cell it's actual value is 1.
And last question: why do you want to do this with VBA, it would be much more simple with worksheet function =IF(G3=1,100,"")

Fill Series, a lot of Series's?

In Excel I've got sequential box numbers in column B, and each box has a couple dozen files that need sequential-by-box place numbers in column C. The way I usually do this is to Fill Series down a selection (selected by hand) of all the cells for that box in Column C, which is fine if you've got a few boxes to do, but now I have several hundred.
[I've got a 394x290 example screenshot I was going to include to show what I mean, but since this is my first post I don't have enough rep, sorry -- link to it on g+ here.]
I thought I could put some VBA code into a macro to select the contiguous cells with the same box number, offset one column right [Offset (0, 1), yeah?], fill series those cells from 1, and go on to the next box. But I haven't had any luck finding anything similar that's been done, nor have I been able to get anything I've looked up to work for this. (Not surprising since I rarely try VBA, hopefully my question's not too noobish for this site.)
From what I can tell, you want the Plc column to fill up series starting from 1 for the same Box Num.
There may exist a fast and quick way but simple method is to go through the rows. Try below:
Sub FillUpPlc()
Dim oRng As Range, n As Long ' n used for series filling
Application.ScreenUpdating = False
n = 1
Set oRng = Range("B2")
Do Until IsEmpty(oRng)
' Increment n if it's same as cell above, otherwise reset to 1
If oRng.Value = oRng.Offset(-1, 0).Value Then
n = n + 1
Else
n = 1
End If
oRng.Offset(0, 1).Value = n ' Store n to next column
Set oRng = oRng.Offset(1, 0) ' Move to next row
Loop
Set oRng = Nothing
Application.ScreenUpdating = True
End Sub
No need to break out the VBA. This can be done with a formula. Starting in C2 and copied down
=IF(B2<>B1,1,C1+1)
Much, much faster than VBA looping through thousands of rows.