I hope I can explain this as I mean it!
I have an SQL query which has been formed as a View to make it easier to pull the data.
However, I have a week number column which gets the date and then calculates the week number. I have everything outputted into an FPDF document, but I need to split the cells after the week number changes, then display a total for that week number.
How would I go about checking when the week number column changes? I just can't think of a solution to this.
This is the code I have currently which doesn't work, there is a very high probability that this isn't right whatsoever.
if iCounter > 1 Then
NewSum = rs("W")
rs.moveprevious
if StrComp(NewSum,rs("W")) = 1 Then
pdf.Cell 15,5,"EOM",1,1,"C",1
else
rs.movenext
pdf.Cell 15,5,"",1,1,"C",1
End if
end if
In this scenario there are different ways to approach this, personally I've always found using Arrays a lot easier more flexible and more efficient than using the ADODB.Recordset.
Once you have a ADODB.Recordset object regardless of the approach (be it ADODB.Command, Recordset.Open() or Connection.Execute()) you can convert it to a two dimensional array using Recordset.GetRows().
Using your example I would structure your code like this;
Please take into consideration this is untested and coded from memory, I just wanted to give you the general gist of how to do this kind of computation in a Classic ASP environment.
Dim rs, data, row, rows
Dim weekno
Dim total_weekno, current_weekno
'Assuming you have instantiated your rs object
'...
'Convert to an Array variable (data)
If Not rs.EOF Then data = rs.GetRows()
'Close and release Recordset from memory
Call rs.Close()
Set rs = Nothing
If IsArray(data) Then
rows = UBound(data, 2)
'Iterate through the array
For row = 0 To rows
'Assuming weekno column is the first in your resultant columns.
weekno = data(0, row)
If weekno = current_weekno Then
'Increment our total for the current weekno by 1.
total_weekno = total_weekno + 1
Else
'Place logic for adding new row to PDF here.
'Use total_weekno to display the incremented total.
'Afterward reset total_weekno for the new current weekno.
total_weekno = 0
'Our weekno has changed so set current weekno.
current_weekno = weekno
End If
Next
End If
Related
I'm using the BaselineWork1 timescaledata to contain a time phased calculation of resource work on individual tasks that I perform on a weekly basis. I want to zero out the previous week's calculation before I populate it with this week's calculation. Short of creating a loop to write zeros to the timescale data for each resource on each task is there a way to do this more efficiently? Could I make the beginning date and end date equal to the project's start and end date and time scale = seconds and the value to write equal to zero? For instance:
For lngCnt1 = 1 To tskCounter.Resources.Count
tskCounter.Assignments.Item(lngCnt1).TimeScaleData(StartDate:=ActiveProject.ProjectStart, EndDate:=ActiveProject.ProjectFinish, _
Type:=pjAssignmentTimescaledBaseline1Work, _
timescalunit:=pjTimescaleMinutes, Count:=1).Item(1).Value = 0
Next lngCnt1
This doesn't seem to work as it only zeros out the baseline1 work field for the date corresponding to the project start date.
To clear time-scaled work from anything but the forecast work field, you do need to loop through every assignment on every task. However, when it comes to the individual time-scale values, you can lump these together by year to reduce the iterations required.
Sub ClearBaseline1Work()
Dim projStart As Date
Dim projEnd As Date
projStart = ActiveProject.ProjectStart
projEnd = ActiveProject.ProjectFinish
Dim tsk As Task
For Each tsk In ActiveProject.Tasks
Dim asn As Assignment
For Each asn In tsk.Assignments
Dim TSValues As TimeScaleValues
Set TSValues = asn.TimeScaleData(projStart, projEnd, pjAssignmentTimescaledBaseline1Work, pjTimescaleYears)
Dim tsv As TimeScaleValue
For Each tsv In TSValues
tsv.Clear
Next tsv
asn.Baseline1Work = 0
Next asn
tsk.Baseline1Work = 0
Next tsk
End Sub
Remember that Baseline1 work values are not automatically updated at the assignment or task level; those values need to be explicitly cleared.
I need to count the number of rows depending on the week and type of the data. I have the excel formula but I want to make it as a VB code yet I don't have that much idea and it is not working.
=IF(AND($N$4="All",$N$5="All"),SUM(('SD'!$I$2:$I$99538='Source'!$B6)*('SD'!$A$2:$A$99538='Source'!C$5)),IF(AND($N$4="All",$N$5<>"All"),SUM(('SD'!$I$2:$I$99538='Source'!$B6)*('SD'!$A$2:$A$99538='Source'!C$5)*('SD'!$B$2:$B$99538='Source'!$N$5)),IF(AND($N$4<>"All",$N$5="All"),SUM(('SD'!$I$2:$I$99538='Source'!$B6)*('SD'!$A$2:$A$99538='Source'!C$5)*('SD'!$K$2:$K$99538='Source'!$N$4)),IF(AND($N$4<>"All",$N$5<>"All"),SUM(('SD'!$I$2:$I$99538='Source'!$B6)*('SD'!$A$2:$A$99538='Source'!C$5)*('SD Raised'!$B$2:$B$99538='Source'!$N$5)*('SD'!$K$2:$K$1048576='Source'!$N$4))))))
I have a sheet where in all datas are captured (SD) and the second one will be the sheet(Source) where i need to count the number of rows available based on the parameter as follow; The week where data belongs and the category of the data.
Edit:
This formula* does not count the data i needed to count. And if possible I want to make it as a VBA code.
This is where the counted data should go. "Weeks are changing depending on the dropdown iput (Max of 4 weeks below from the selected week)"
This image shows the data where i need to capture and count the number of category based on the weeks and category. (Sample only)
I guess, if it's the right point you're hitting DoktorOSwaldo, better use the Range().Rows.Count property rather than scrolling through allRows.
Hope this helps.
Hadi
so i have to guess a bit what you want, but if you want to Count specific rows in Excel vba you can use something like this:
Dim allRows As Variant
Dim i As Long
Dim count as Long
count = 0
allRows = Tabelle5.Range("A" & start_row, end_column & last_row)
For i = 1 To UBound(allRows)
If allRows(i, 1) = *category* and allRows(i,2) = *week* Then
count = count + 1
End If
Next
To find right range, there are multiple possible solution. I use this, maybe it is not the best, but works fine for me:
Private Function last_row() As Integer
Dim rangeObj As Range
Set rangeObj = Tabelle5.Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If rangeObj Is Nothing Then
last_row = start_row
Else
last_row = rangeObj.row
End If
End Function
Public Function start_row() As Integer
start_row = 2
End Function
The data I have can be simplified to this:
http://i.imgur.com/mn5GgrQ.png
In this example, I would like to delete the data associated with track 2, since it has only 3 frames associated with it. All data with more than 3 associated frames can stay.
The frame number does not always start from 1, as I've tried to demonstrate. The track number will always be the same number consecutively for as many frames as are tracked. I was thinking of using a function to append 1 to a variable for every consecutive value in column A, then performing a test to see if this value is equal >= 3. If so, then go onto the next integer in A, if no, then delete all rows marked with that integer (2, in this case).
Is this possible with Visual Basic in an Excel Macro, and can anyone give me some starting tips on what functions I might be able to use? Complete novice here. I haven't found anything similar for VBA, only for R.
I assume you understand the code by reading it.
Option Explicit
Public Function GetCountOfRowsForEachTrack(ByVal sourceColumn As Range) As _
Scripting.Dictionary
Dim cell As Range
Dim trackValue As String
Dim groupedData As Scripting.Dictionary
Set groupedData = New Scripting.Dictionary
For Each cell In sourceColumn
trackValue = cell.Value
If groupedData.Exists(trackValue) Then
groupedData(trackValue) = cell.Address(False, False) + "," + groupedData(trackValue)
Else
groupedData(trackValue) = cell.Address(False, False)
End If
Next
Set GetCountOfRowsForEachTrack = groupedData
End Function
Public Sub DeleteRowsWhereTrackLTE3()
Dim groupedData As Scripting.Dictionary
Set groupedData = GetCountOfRowsForEachTrack(Range("A2:A15"))
Dim cellsToBeDeleted As String
Dim item
For Each item In groupedData.Items
If UBound(Split(item, ",")) <= 2 Then
cellsToBeDeleted = item + IIf(cellsToBeDeleted <> "", "," + cellsToBeDeleted, "")
End If
Next
Range(cellsToBeDeleted).EntireRow.Delete
End Sub
GetCountOfRowsForEachTrack is a function returning a dictionary (which stores track number as key, cell address associated with that track as string)
DeleteRowsWhereTrackLTE3 is the procedure which uses GetCountOfRowsForEachTrack to get the aggregated info of Track numbers and cells associated with it. This method loops through the dictionary and checks if the number of cells associated with track is <=2 (because splitting the string returns an array which starts from 0). It builds a string of address of such cells and deletes it all at once towards the end.
Note:
Add the following code in a bas module (or a specific sheet where
you have the data).
Add reference to "Microsoft Scripting.Runtime" library. Inside VBA, click on "Tools" -> "References" menu. Tick the "Microsoft Scripting.Runtime" and click on OK.
I have used A2:A15 as an example. Please modify it as per your cell range.
The assumption is that you don't have thousands of cells to be deleted, in which case the method could fail.
Make a call to DeleteRowsWhereTrackLTE3 to remove such rows.
i have a MS access database with a table such as the one below and i am trying to figure out the sql needed to determine the total number of times the date changes across all the fields for each defectID record.
also, note that each day i add a field to the table, so if this can be made dynamic that would be best.
when there are no dates i would like the result to display 0 (zero)
thanks all
you definitely have a normalization issue here.
you should consider moving the date to another table - maybe similar to the following:
Retest Estimate
-----------------
defect_id
estimate_date
ready_date
You are treating a database like a spread sheet. It would be better to set up a table on these lines:
DefectID
TestDate
Est_ReadyForRetest
This means that you are adding records each day, rather than fields. It will also make queries easier.
I agree with the suggestion that the data ought to be normalized, but then you have a different problem for answering the question, one that I'm not sure how you'd do it in SQL (since it is based on the order of the records). That is, you'd have to walk a recordset to do it. I guess a correlated subquery could do the trick, but it would have to based on something that can be ordered.
My SQL skills are not fabulous, so in the abstract I won't suggest a SQL solution, but maybe somebody else will.
Instead, I'll suggest a function that could return the answer in the original unnormalized data structure. I base this on my existing iMax() function, which goes like this:
Public Function iMax(ParamArray p()) As Variant
' Idea from Trevor Best in Usenet MessageID
' rib5dv45ko62adf2v0d1cot4kiu5t8mbdp#4ax.com
Dim i As Long
Dim lngUBound As Long
Dim v As Variant
v = p(LBound(p))
lngUBound = UBound(p)
For i = LBound(p) + 1 To lngUBound
If v < p(i) Then
v = p(i)
End If
Next
iMax = v
End Function
The idea is using a parameter array to pass the values to the function, and then walking the array to get the information you need. In this case, you'd want to walk the array and count the number of times it changes, something like this:
Public Function CountChange(ParamArray varInput()) As Long
Dim varValue As Variant
Dim varPrevious As Variant
Dim lngCount As Long
varPrevious = varInput(0)
For Each varValue In varInput()
If varValue <> varPrevious Then
lngCount = lngCount + 1
End If
varPrevious = varValue
Next varValue
CountChange = lngCount
End Function
I haven't tested that very thoroughly, and it doesn't deal with Nulls at all, but that's the idea -- it's very useful concept for comparing data from fields within a single row.
I want to iterate over all rows of a MS-Word mail merge data source and extract the relevant data into an XML.
I'm currently using this code:
Imports Microsoft.Office.Interop
Do
objXW.WriteStartElement("Recipient")
Dim objDataFields As Word.MailMergeDataFields = DataSource.DataFields
For Each FieldIndex As Integer In mdictMergeFields.Keys
strValue = objDataFields.Item(FieldIndex).Value
If Not String.IsNullOrEmpty(strValue) Then
strName = mdictMergeFields(FieldIndex)
objXW.WriteElementString(strName, strValue)
End If
Next
objXW.WriteEndElement()
If DataSource.ActiveRecord = LastRecord Then
Exit Do
Else
DataSource.ActiveRecord = Word.WdMailMergeActiveRecord.wdNextDataSourceRecord
End If
Loop
And it turns out to be a little sluggish (About 1 second for each row). Is there any way to do it faster?
My fantasy is finding a function like MailMergeDataSource.ToDatatable and then inspecting the datatable.
Any time you're iterating through something row by row, and then doing some kind of processing on each row, is going to get a little slow.
I would be inclined to approach this problem by having a step before this which prepared the mdictMergeFields collection so that it only contained elements that were not 'null or empty', this will mean you won't have to check for that on each iteration. You could do this in process, or 'sneakily' in the background while the user is doing something else.
The other thing to try (might help!) is to change the "Do... Loop" block so that you're not checking at the end of each imported row whether or the record is the 'last record'. Instead, get a count of the records, and then compare the current index to the knowm maximum (which might be quicker)
I.E.:
Dim i, x as Integer
i = ActiveDocument.MailMerge.DataSource.RecordCount
Do While x < i
objXW.WriteStartElement("Recipient")
Dim objDataFields As Word.MailMergeDataFields = DataSource.DataFields
For Each FieldIndex As Integer In mdictMergeFields.Keys
strValue = objDataFields.Item(FieldIndex).Value
If Not String.IsNullOrEmpty(strValue) Then
strName = mdictMergeFields(FieldIndex)
objXW.WriteElementString(strName, strValue)
End If
Next
objXW.WriteEndElement()
x += 1
Loop
I don't really work with the Office Interop much, but hopefully this might offer some assistance! Post back, let me know how it goes.
/Richard.