I'm trying to print a list of dates using a for loop. I'm getting an error saying 'AddDays' is not a member of 'System.Array'.
Dim payDates(10) as Date
For index As Integer = 1 to 10
Redim Preserve payDates(index)
payDates(index) = payDates.AddDays(1)
index +=1
NEXT
Response.Write(payDates)
I'm no vb expert, but you need to access the index of the array, not the array itself:
Dim payDates(10) as Date
For index As Integer = 1 to 10
Redim Preserve payDates(index)
payDates(index) = payDates(index).AddDays(1)
index +=1
NEXT
Response.Write(payDates)
Also you migzht want to write every date. In this case change you code to this:
Dim payDates(10) as Date
For index As Integer = 1 to 10
Redim Preserve payDates(index)
payDates(index) = payDates(index).AddDays(1)
Response.Write(payDates(index))
index +=1
NEXT
In essence:
payDates is of type System.Array
payDates(index) contains a DateTime variable at the position index, where index is of type int
Well, AddDays isn't a member of System.Array. But you're trying to call it anyway:
payDates.AddDays(1)
If you're trying to get a modified date, reference the date element of the array. Something like this:
payDates(index).AddDays(1)
(Note that if you're looking to display this information on a web page, it's a lot better to set the information on elements of that page than to use Response.Write(). You have very little control over where Response.Write() emits its output in the resulting page.)
Related
I am currently working on a project and am running into an error that says: Syntax error in aggregate argument: Expecting a single column argument with possible 'Child' qualifier. I have a column named "Total#" in a BusinessAnalytics data table. I want to sum the column together so that I can use it to calculate a percentage of members and percentage of nonmembers. How can I fix this?
My code for a data table with running totals
Dim decTotalNumber As Decimal
Dim decPercentSales As Decimal
Dim intRow As Integer
If chkRewards.Checked = True Then
intRow = 1 'member
Else
intRow = 0 'nonmember
End If
With BusinessAnalytics.Rows(intRow)
.Item("Total#") += 1
decTotalNumber = BusinessAnalytics.Compute("SUM(Total#)", Nothing)
decPercentSales = Convert.ToDecimal(.Item("Total#")) / decTotalNumber
.Item("%Total") = decPercentSales.ToString("P1")
End With
GridView3.DataSource = BusinessAnalytics
GridView3.DataBind()
Your column name contains non-alphanumeric characters, so it should be wrapped in square brackets or "`" (grave accent) quotes.
Expression
So your statement should be:
decTotalNumber = BusinessAnalytics.Compute("SUM([Total#])", Nothing)
I get the following error when trying to create a default row in the asp.net dropdown: Conversion from string "x" to type 'Integer' is not valid.
CmbSalesAgents is the drop down control.
DefaultSalesAgent is the entity object (has values)
x is a concatenation of a numeric value and a string
**
Dim DefaultSalesAgent = (From o In db.PayoutRegisters
Join s In db.SalesAgents On s.SalesAgentId Equals o.SalesAgentID
Where o.PayoutRegisterID = PayoutRegisterID
Select o.PayoutRegisterID, x = s.CSRName + " (" + o.PaidThruDate.ToString + ")").ToList
If DefaultSalesAgent.Count > 0 Then
CmbSalesAgents.Items.Insert(0, New ListItem(DefaultSalesAgent.Item("x").ToString, PayoutRegisterID))
Else
CmbSalesAgents.Items.Insert(0, New ListItem("Select Sales Agent Payout Register", 0))
End If
Since DefaultSalesAgent is a list object then you should access its items through integer index not a string:
DefaultSalesAgent.Item(integer_index)
If you specifically need to insert the row based off a string value, you can replace
DefaultSalesAgent.Item("x")
With
DefaultSalesAgent.Item(DefaultSalesAgent.FindIndex(x => x.StartsWith("x")));
You can also use contains instead of startswith depending on your needs. Please note this is only if you specifically need to look for strings as it's a lot more expensive than accessing an index in the list.
After searching the forum, I did not find a good solution for this question. If I missed it, please tell me.
I need to count the unique values in one column in EXCEL 2010.
The worksheet has 1 million rows and 10 columns. All cell values are string or numbers.
I used the solution at Count unique values in a column in Excel
=SUMPRODUCT((A2:A1000000<>"")/COUNTIF(A2:A100000,A2:A1000000&""))
But, it runs so long time that the EXCEL is almost frozen. And, it generates 25 processes in Win 7.
Are there more efficient ways to do it?
Also, in the column, all values have for format of
AX_Y
here, A is a character, X is an integer, Y is an integer from 1 to 10.
For example, A5389579_10
I need to cut off the part after (including) undersocre. for the example,
A5389579
This is what I need to count as unique values in all cells in one column.
For example, A5389579_10
A1543848_6
A5389579_8
Here, the unique value has 2 after removing the part after underscore.
How to do it in EXCEL VBA and R (if no efficient solution for EXCEL)?
If you want to do this by VBA, you can take advantage of the Collection object. Since collections can only contain unique values, trying to add all of your input data to a collection will result in an array of unique values. The code below takes all the variables in a selected range and then outputs an array with distinct values to an other sheet (in this case a sheet named Output).
Sub ReturnDistinct()
Dim Cell As Range
Dim i As Integer
Dim DistCol As New Collection
Dim DistArr()
Dim OutSht As Worksheet
Dim LookupVal As String
Set OutSht = ActiveWorkbook.Sheets("Output") '<~~ Define sheet to putput array
If TypeName(Selection) <> "Range" Then Exit Sub
'Add all distinct values to collection
For Each Cell In Selection
If InStr(Cell.Value, "_") > 0 Then
LookupVal = Mid(Cell.Value, 1, InStr(Cell.Value, "_") - 1)
Else
LookupVal = Cell.Value
End If
On Error Resume Next
DistCol.Add LookupVal, CStr(LookupVal)
On Error GoTo 0
Next Cell
'Write collection to array
ReDim DistArr(1 To DistCol.Count, 1 To 1)
For i = 1 To DistCol.Count Step 1
DistArr(i, 1) = DistCol.Item(i)
Next i
'Outputs distinct values
OutSht.Range("A1:A" & UBound(DistArr)).Value = DistArr
End Sub
Note that since this code writes all the distinct values to a single column in the OutSht-sheet, this will return an error if there are more than 1,048,576 distinct values in your dataset. In that case you would have to split the data to be filled into multiple output columns.
For your specific request to count, use the below in a formula like =COUNTA(GetUniques(LEFT("A1:A100000",FIND("_","A1:A100000")-1)) entered as an array formula with Ctrl+Shift+Enter.
It also accepts multiple ranges / values (e.g. GetUniques("A1:A10","B2:E4"))
Function GetUniques(ParamArray args())
Dim arg, ele, arr, i As Long
Dim c As Collection
Set c = New Collection
For Each arg In args
If TypeOf arg Is Range Then
If arg.Count = 1 Then
arr = array(arg.value)
Else
arr = arg.Value
End If
ElseIf VarType(arg) > vbArray Then
arr = arg
Else
arr = Array(arg)
End If
For Each ele In arr
On Error Resume Next
c.Add ele, VarType(ele) & "|" & CStr(ele)
On Error GoTo 0
Next ele
Next arg
If c.Count > 0 Then
ReDim arr(0 To c.Count - 1)
For i = 0 To UBound(arr)
arr(i) = c(i + 1)
Next i
Set c = Nothing
GetUniques = arr
End If
End Function
edit: added a performance optimisation for ranges (loads them at once into an array - much faster than enumerating through a range)
In R:
# sample data
df <- data.frame(x=1:1000000,
y=sample(1e6:(1e7-1),1e6,replace=T))
df$y <- paste0("A",df$y,"_",sample(1:10,1e6,replace=T))
# this does the work...
length(unique(sub("_[0-9]+","",df$y)))
# [1] 946442
# and it's fast...
system.time(length(unique(sub("_[0-9]+","",df$y))))
# user system elapsed
# 2.01 0.00 2.02
In excel 2010... in the next column add (if original data was in A:A add in B1)
= 1/COUNTIF(A:A,A1) and copy down col B to the bottom of your data. Depending on your PC it may chug away calculating for a long time, but it will work. Then copy col B & paste values over itself.
Then SUM col B
I have one data table in VB page which contain bulk data.In that data table one column named as vType and values in that column is one of Pr defined values such as 'A','B','C','D' etc , which comes from one Datable.
Now I want count of each type at the end.
For ex : CountA = 20,CountB=25 and so on .
Till now I have compared Each value using If condition which is static
For each dr as dataRow in dsType.rows
If dr("vType") = 'A' Then
CountA += 1
ElseIf dr("vType") = 'B' Then
CountB +=1
Next dr
and this If condition will repeat depend upon no of types in that data table (at max 8 fix values) I want to do this in single if condition ( Dynamic if Possible) Can I Count these values and store the same into single varaible? appreciate for you prompt reply.
You can use Linq-To-DataSet and Enumerable.GroupBy + Enumerable.Count on each group:
Dim typeGroups = dsType.AsEnumerable().
GroupBy(Function(row) row.Field(Of String)("vType")).
Select(Function(g) New With{ .Type = g.Key, .Count = g.Count(), .TypeGroup = g })
Note that New With creates an anonymous type in VB.NET with custom properties. So like a class on-the-fly which you can use in the current method.
Now you can enumerate the query with For Each:
For Each typeGroup In typeGroups
Console.WriteLine("Type:{0} Count:{1}", typeGroup.Type, typeGroup.Count)
Next
I cannot use Linq, i need to use simple vb only
Then use a Dictionary:
Dim typeCounts = New Dictionary(Of String, Integer)
For Each row As DataRow In dsType.Rows
Dim type = row.Field(Of String)("vType")
If (typeCounts.ContainsKey(type)) Then
typeCounts(type) += 1
Else
typeCounts.Add(type, 1)
End If
Next
Now you have a dictionary where the key is the type and the value is the count of the rows with this type.
why not getting the pretend result from the db itself?
Like so:
select count(*), vType
from someTable
group by vType
Not so sure about your question .. but this is what I've considered ..
You can make it as Sub ..
Sub AssignIncr(ByVal ds as DataSet,byval sFi as String,byval sCrit as String,ByRef Counter as Integer)
For each dr as dataRow in ds.rows
If dr(sFi) = sCrit Then Counter += 1
Next dr
End Sub
So you may use it by ..
AssignIncr(dsType,"vType","A",CountA)
I'm writing in ASP.NET 4 / VB.NET. I am querying an MSSQL database and sometimes have records come back with no results...so I enclosed the call I was making upon the results in an If..Else clause to set a default value if the database comes back with no results...but now I am getting this "Object variable or With block variable not set error". Here is the relevant code:
Dim clcfirst
Dim rhcfirst
Dim clcdate As Date
Dim rhcdate As Date
If IsNothing(clcexists) Then
clcfirst = Date.Now.Subtract(year)
rhcfirst = Date.Now.Subtract(year)
clcdate = clcfirst
rhcdate = rhcfirst
Else
clcfirst = clcexists.FirstOrDefault()
rhcfirst = rhcexists.FirstOrDefault()
clcdate = clcfirst.SignatureDate
rhcdate = rhcfirst.SignatureDate
End If
Where is the DateTime year variable being set? Could that be null?
If you want to subtract a year, you could just do:
clcdate = Date.Now.AddYears(-1)
rhcdate = Date.Now.AddYears(-1)