worksheetfunction.aggregate ignore hidden/error/0 values - vba

this code works until the loops encounter a blank/error cell value
Dim ws1 As Worksheet, wstest As Worksheet, wskb As Worksheet
Dim lastrowinc As Long, curRow As Long, lastrowkb As Long
Dim medianvalue As Integer
Dim critvalue As String
'Sheet to look up Critvalue
Set ws1 = Sheets("Incident")
'Sheet where to store Medianvalue
Set wstest = Sheets("Sheet3")
'Sheet where to get Critvalue (A2 onwards)
Set wskb = Sheets("KB Articles")
'For autofilter criteria
lastrowinc = ws1.Range("A" & Rows.Count).End(xlUp).Row
lastrowkb = wskb.Range("A" & Rows.Count).End(xlUp).Row
For curRow = 2 To lastrowkb
critvalue = wskb.Range("A" & curRow).Value
ws1.Range("M1:A" & lastrowinc).AutoFilter field:=13, Criteria1:=critvalue
medianvalue = WorksheetFunction.Aggregate(12, 5, Columns(2))
wstest.Range("A" & Rows.Count).End(xlUp).Offset(1) = medianvalue
Next curRow
now according to this page we can use 7 as Arg2 to ignore hidden and error. I tried but it still gives an error 1004 on this line: medianvalue = WorksheetFunction.Aggregate(12, 5, Columns(2))
(note i tried 5 and 7 but still the same error). i even tried to set all blank cells to cause an excel error (#N/A) but to no avail. it works until it meets a BLANK/error cell
i also have a question with the result output. why is it displaying a whole number? I had this working with on a manual autofilter criteria before (with a texbox) and it displays a value with decimals but when i looped it up it a whole number.
thanks guys.

You can test for the existence of at least one numberic value using the Count function.
If WorksheetFunction.Count(ws1.Columns(2).SpecialCells(xlCellTypeVisible)) > 0 Then
medianvalue = WorksheetFunction.Aggregate(12, 5, ws1.Columns(2))
Else
medianvalue = some value that is meaningful to you
End If

Related

Different sheet pasting

I have written a code which gives me the errors (if any cell is non numeric) in a separate sheet called "Error_sheet".
But the output is a bit clumsy as it gives me non numeric cell address in a confusing fashion. Like the errors will not be pasted one after another. There will be some blanks in between if there are more than one non Numeric cells.
Sub Test()
Dim LastRow As Long, i As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
For i = 2 To LastRow
If IsNumeric(Range("A" & i).Value) Then
Else
Sheets("Error").Range("A" & Row).Value = "Error in" & i & " row of ColumnNAme"
Row = Row + 1
End If
Next i
End Sub
It gives me output like shown below but can I get the output like Error in 7,14 rows of column name in a desired cell of "Error_sheet".
[![Output][1]][1]
[1]: https://i.stack.imgur.com/JqXwq.png
My understanding of what you've written is that you want something like this.
Option Explicit
Sub Test()
' Unqualified book/sheet below, means code will always run the isnumeric check on the cells of the active sheet. Is that what you want? '
Dim LastRow As Long
LastRow = Cells(Rows.Count, "A").End(xlUp).Row
Dim Index as long
Dim i As Long
Dim NonNumericRows() as string
Redim NonNumericRows(1 to lastrow)
For i = 2 To LastRow
If not(IsNumeric(Range("A" & i).Value)) Then
Index = index + 1
NonNumericRows(Index) = cstr(i)
End if
Next i
Redim preserve NonNumericRows(1 to index)
Sheets("Error").Range("A1").Value = "Error in row(s): " & strings.join(nonnumericrows,", ") & " of ColumnNAme"
End Sub
Hope it works or helps.
Like QHarr suggested, using Option Explicit is normally a good idea, and try not to use VBA operators as variables.
Also when working with more than 1 sheet, its best to define each in the code. I dont know what your first sheet is called, so please change the line: Set shSource = Sheets("Sheet1") to suit:
Option Explicit
Sub SubErrorSheet()
Dim lr As Long, i As Long
Dim shSource As Worksheet, shError As Worksheet
Set shSource = Sheets("Sheet1")
Set shError = Sheets("Error")
lr = shSource.Range("A" & Rows.count).End(xlUp).Row
For i = 2 To lr
If Not IsNumeric(shSource.Range("A" & i).Value) Then
shError.Range("A" & Rows.count).End(xlUp).Offset(1, 0).Value = "Error in row " & i & " of ColumnNAme"
End If
Next i
End Sub

VBA: Addition in cells

I'm sorting through data and need it to be formatted the same way. The input might have cells with
6+18
12
3
5+14
20
And I want to make them all integers. I've written this so far:
If InStr(data.Cells(x, 8), "+") > 0 Then
'Still trying to figure out this part
Else
calc.Cells((lrcalc + 1), (col + s)).Value = data.Cells(x, 8)
End If
How would I add the value on the left of the "+" sign to the value on the right?
Well there is no need to check for +. Simply add an = sign in each cell and let excel calculate it ;)
Sub Sample()
Dim lRow As Long, i As Long
Dim ws As Worksheet
'~~> Change this to the relevant sheet
Set ws = ActiveSheet
With ws
'~~> Find last row
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 1 To lRow
With .Range("A" & i)
.Formula = "=" & .Value
.Value = .Value
End With
Next i
End With
End Sub
Screenshot

Excel VBA - Select a range using variables & COUNTA

Excel VBA - Select a range using variables & COUNTA
Hi Staked VBA Kings & Queens, I'm trying to learn Excel VBA. A simple task I would like to do is select all the contagious cells in a report dump I get from sales. Simple i'm sure, but I am a total beginner at VBA.
Ok Report Info:
The report is a set number of columns (31). Although I would like to build a bit of variability into my code to accommodate a change in column numbers.
The report grows by number of rows each week, some times less, sometimes more. But Always starts at cell [A4].
I though of using COUNTA function to count used number of rows, then set that as a variable. Similar with rows.
This is what I came up with, although I get a "Run-time Error '1004': Method 'Range' of object'_Global failed... can anyone help me out".
For me the key is to learn VBA using task I need getting done. I understand the logic behind my code, but not exactly the write way to write it. If some proposes a totally different code I might get lost.
But I am open minded.
Sub ReportArea()
Dim numofrows As Integer
Dim numofcols As Integer
Dim mylastcell As String
Dim myrange As Range
Worksheets("Sheet1").Select
numofrows = WorksheetFunction.CountA(Range("AE:AE"))
numofcols = WorksheetFunction.CountA(Range("4:4"))
Set myrange = Range(Cells(4, 1), Cells(numofrows, numofcols))
Range(myrange).Select
End Sub
P.S I did try read slimier trends but only got confused as the solution where very involved.
Find last row and last column
Sub Sht1Rng()
Dim ws As Worksheet
Dim numofrows As Long
Dim numofcols As Long
Dim myrange As Range
Set ws = Sheets("Sheet1")
With ws
numofrows = .Cells(.Rows.Count, "AE").End(xlUp).Row
numofcols = .Cells(4, .Columns.Count).End(xlToLeft).Column
Set myrange = .Range(.Cells(4, 1), .Cells(numofrows, numofcols))
End With
MsgBox myrange.Address
End Sub
You can also use this code.
Sub SelectLastCellInInSheet()
Dim Rws As Long, Col As Integer, r As Range, fRng As Range
Set r = Range("A1")
Rws = Cells.Find(what:="*", after:=r, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
Col = Cells.Find(what:="*", after:=r, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Set fRng = Range(Cells(2, 1), Cells(Rws, Col)) ' range A2 to last cell on sheet
fRng.Select 'or whatever you want to do with the range
End Sub
Further to my above comment, is this what you are trying?
Sub ReportArea()
Dim ws As Worksheet
Dim Lrow As Long
Dim myrange As Range
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
'~~> Find Last row of COl AE. Change it to the relevant column
Lrow = .Range("AE" & .Rows.Count).End(xlUp).Row
Set myrange = .Range("A4:AE" & Lrow)
With myrange
'
'~~> Do whatever you want to do with the range
'
End With
End With
End Sub
Note: Also you don't need to select a range/worksheet. Work with objects. Interesting Read
alternative solutions to already posted:
1:
Dim LRow&, LColumn&
Lrow = Sheets("SheetName").Cells.SpecialCells(xlCellTypeLastCell).Row
LColumn = Sheets("SheetName").Cells.SpecialCells(xlCellTypeLastCell).Column
MsgBox "Last Row is: " & Lrow & ", Last Column is: " & LColumn
2:
Dim x As Range
Set x = Range(Split(Sheets("SheetName").UsedRange.Address(0, 0), ":")(1))
MsgBox "Last Row is: " & x.Row & ", Last Column is: " & x.Column
output result

Need to find the last row in a spreadsheet before copying and pasting data from Sheet 1 to Sheet 2

This site has helped me immensely with VBA for a while now, so thanks for that! But I just can't seem to get this code to work and I've look at so many examples. What's happening is that I'm archiving data on another sheet once the current date is 4 days ahead of the due date. Everything works like it should, but every time the macro executes, the data on sheet2 is erased and copied over. I need my code to find the last row on sheet2 and copy the data from sheet1 to sheet2 so all the data is there. Thanks!
Sub archive()
Dim LastRow As Long
Dim i As Long
LastRow = Range("M" & Rows.Count).End(xlUp).Row
For i = 3 To LastRow
If Worksheets("Sheet1").Range("M" & i) - Date <= -4 And Worksheets("Sheet1").Range("N" & i).Value = "DONE" Then
Sheet2.Select
Range("A" & i).EntireRow.Value = Sheet1.Range("M" & i).EntireRow.Value
Sheet1.Range("M" & i).EntireRow.Delete
End If
If Worksheets("Sheet1").Range("L" & i) = "" Then
Exit For
End If
Next i
End Sub
Here I've taken your code and changed it to use worksheet objects. I've not tested this on any data as you haven't provided any to use, but it gives you an idea of how to implement it.
Also, in your code you weren't finding the last row of Sheet2, you were putting the data in row i, which starts at 3.
You also need to watch out when you delete the row of data from sheet1, as this shifts the rest of the data up, so the next iteration of the loop may not find the next row of data/ skip a row of data.
Sub archive()
Dim LastRow As Long
Dim LastRowSht2 As Long
Dim i As Long
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim rowCount As Long
Set sht1 = Worksheets("Sheet1")
Set sht2 = Worksheets("Sheet2")
LastRow = sht1.Range("M" & Rows.Count).End(xlUp).Row
rowCount = 3
For i = 3 To LastRow
If sht1.Range("M" & rowCount) - Date <= -4 And sht1.Range("N" & rowCount).Value = "DONE" Then
LastRowSht2 = sht2.Range("A" & Rows.Count).End(xlUp).Row + 1 '+1 so it doesn't overwrite the last row
sht2.Range("A" & LastRowSht2).EntireRow.Value = sht1.Range("M" & rowCount).EntireRow.Value
sht1.Range("M" & rowCount).EntireRow.Delete
Else
rowCount = rowCount + 1
End If
If sht1.Range("L" & rowCount) = "" Then
Exit For
End If
Next i
' clean up
set sht1 = nothing
set sht2 = nothing
End Sub

How to return value from VLOOKUP into a cell?

I have the following piece of code for Vlookup. The function works fine but the found out value aint getting displayed in the cell. However if i had a used Msgbox function the found out value is shown. The question is doesnt VLOOKUP result be captured in a cell?
Sub Example_of_Vlookup()
Dim lookFor As Range
Dim rng As Range
Dim col As Integer
Dim found As String
Dim lastrowrange As Long
Dim area As Range
lastrowrange = [A65536].End(xlUp).Row
Set lookFor = Sheets("Sheet2").Range("b2")
Set rng = Sheets("Sheet2").Columns("t:u")
Set taxRange = Range("f2", Cells(lastrowrange, 22))
col = 2
On Error Resume Next
For i = 1 To lastrowrange
found = Application.VLookup("B2", "T1:U4", 2, True)
If IsError(found) Then
MsgBox lookFor & " not found"
Else
area.Cells(i, 2).Value = found
End If
Next i
On Error GoTo 0
End Sub
You did not set the range "area" equal to anything, so this line won't show your answer properly:
area.Cells(i, 2).Value = found
Change area.Cells(i,2).value to sheets("Sheet2").Cells(i,2).value or wherever you want your answer to show. Or, set area equal to something if you want to use area.cells.
Idea is simple - I have country names in Column B.Inention is to pull out the Area under which country belongs - My look up values are in column S(country) and T(area) and display the result in column F – Sayanth Sasidharan 25 mins ago
If my understanding is correct as per your explanation then you do not need to use a loop. Let Excel do the Dirty Work ;) You will end up with far less code.
Let's say your sheet looks like this
Logic:
Find the last row of Col B
Insert the Vlookup formula in F1:F & LastRow in one go
Convert them to values.
Code:
Option Explicit
Sub Example_of_Vlookup()
Dim ws As Worksheet
Dim lRow As Long
Set ws = ThisWorkbook.Sheets("Sheet2")
With ws
lRow = .Range("B" & .Rows.Count).End(xlUp).Row
'~~> =IF(ISERROR(VLOOKUP(B1,S:T,2,0)),"",VLOOKUP(B1,S:T,2,0))
.Range("F1:F" & lRow).Formula = _
"=IF(ISERROR(VLOOKUP(RC[-4],C[13]:C[14],2,0)),"""",VLOOKUP(RC[-4],C[13]:C[14],2,0))"
.Range("F1:F" & lRow).Value = .Range("F1:F" & lRow).Value
End With
End Sub
Result: