display listview items in excel sheet - wpf

I am displaying my results from an SQL search in excel from a WPF application. It initally displays them in a listview and the user can select the option to export to excel which is working fine.
The error i am having is, if there are say 5 results in the SQL result and displayed in the listview, when i export to excel it is only displaying 4 results plus the SQL table headings...
For i As Integer = 1 To dtMainSQLData.Rows.Count
For j As Integer = 1 To dtMainSQLData.Columns.Count
If i = 1 Then
sheet.Cells(i, j) = dcCollection(j - 1).ToString()
Else
sheet.Cells(i, j) = dtMainSQLData.Rows(i - 1)(j - 1).ToString()
End If
Next
Next
Does anyone see a problem with the about loop for printing out the SQL results to excel

this is your problem:
For i As Integer = 1 To dtMainSQLData.Rows.Count
If you skip the first and you handle decreasing it by 1 when you access your items, you must go up to To dtMainSQLData.Rows.Count + 1
Personally I would start from 0 like this:
For i As Integer = 0 To dtMainSQLData.Rows.Count
For j As Integer = 0 To dtMainSQLData.Columns.Count
If i = 0 Then
sheet.Cells(i + 1, j + 1) = dcCollection(j).ToString()
Else
sheet.Cells(i + 1, j + 1) = dtMainSQLData.Rows(i)(j).ToString()
End If
Next
Next

After debugging csharpwinphonexaml's answer I got it working. I have to add an additional IF to check if it was at the last position.
For i As Integer = 0 To dtMainSQLData.Rows.Count
For j As Integer = 0 To dtMainSQLData.Columns.Count - 1
If i = 0 Then
sheet.Cells(i + 1, j + 1) = dtMainSQLData.Columns(j).ToString()
ElseIf i = dtMainSQLData.Rows.Count Then
sheet.Cells(i + 1, j + 1) = dtMainSQLData.Rows(0)(j).ToString()
Else
sheet.Cells(i + 1, j + 1) = dtMainSQLData.Rows(i)(j).ToString()
End If
Next
Next

Related

VBA Runtime Error 9 (Excel 2007)

i have got the following problem. I am creating an excel worksheet with active x elements to calculate several values (for a class in university). And in the following code i sometimes (not everytime) get the runtime error 9 that the index is out of range (hopefully i translated it correctly into english). I am new to vba. I know that there are several similar problems already asked but i have a huge problem to adapt the solutions to my code as i don't really understand either the problem in my code as also the solutions of their problems.
I marked the line for which the error occurs with stars.
I would be really thankful if anybody could explain, why this problem occurs in my code sometimes and how to solve it properly.
Thank you in advance.
Here's the code:
Sub calcinull()
Dim ione(4), itwo(4), ii, ints(4), cs(4), io, it As Double
Dim a, b, c As Double
ione(0) = 0
ione(1) = 10
ione(2) = 20
ione(3) = 30
ione(4) = 40
itwo(0) = 100
itwo(1) = 90
itwo(2) = 80
itwo(3) = 70
itwo(4) = 60
For b = 0 To 4
ii = ione(b) + (((itwo(b) - ione(b)) * (NPV(ione(b))) / (NPV(ione(b)) - NPV(itwo(b)))))
ints(b) = ii
cs(b) = NPV(ii)
Next b
Dim AbsInt(4), AbsCs(4) As Double
For a = 0 To 4
AbsInt(a) = VBA.Abs(ints(a))
AbsCs(a) = VBA.Abs(cs(a))
Next a
Dim pos As Integer
pos = Application.Match(Application.Min(AbsCs), AbsCs, 0)
*ii = ints(pos)*
If NPV(ii) > 0 Then
io = ii
If pos > 0 Then
it = itwo(pos - 1)
Else
it = itwo(0)
End If
ElseIf NPV(ii) < 0 Then
it = ii
If pos > 0 Then
io = ione(pos - 1)
Else
io = ione(0)
End If
ElseIf NPV(ii) = 0 Then
inull = ii
End If
For c = 1 To 30
Do Until (NPV(io) - NPV(it)) <> 0
io = io - 0.1
it = it + 0.1
Loop
ii = io + (((it - io) * (NPV(io)) / (NPV(io) - NPV(it))))
If NPV(ii) > 0 Then
io = ii
If it > (io + 0.5) Then
it = it - 0.5
End If
ElseIf NPV(ii) < 0 Then
it = ii
If io < (it - 0.5) Then
io = io + 0.5
End If
ElseIf NPV(ii) = 0 Then
inull = ii
Exit For
End If
Next c
inull = ii
End Sub
As ints is an array with 5 elements (0..4), probably pos is > 4 when this error occurs.
If you can't tell why, maybe put something like this behind the Match-Statement and set a breakpoint to the print while testing.
if pos < 0 or pos > 4 then
debug.print pos & " is off"
end if
Alright guys, i solved it. The problem was, that the arrays uses indices from 0 to x, whereas the position gives the nth position of the array, which means, that my "pos"-variable is always one integer above the array-index.
Thank you all for your help!

Excel VBA to SQL Server - Transition Matrix

I have code in VBA that works to generate a transition matrix on data in excel. I now have access to a huge SQL DB with ~2MM rows of information and would like to generate a transition matrix which looks something like this:
In any case here is the VBA code:
Option Explicit
Function COHORT(id, dat, rat, _
Optional classes As Integer, Optional ystart, Optional yend)
'Function is written for data sorted according to issuers and rating dates (ascending),
'rating classes numbered from 1 to classes, last rating class=default, not rated has number "0"
If IsMissing(ystart) Then ystart = Year(Application.WorksheetFunction.min(dat))
If IsMissing(yend) Then yend = Year(Application.WorksheetFunction.Max(dat)) - 1
If classes = 0 Then classes = Application.WorksheetFunction.Max(rat)
Dim obs As Long, k As Long, kn As Long, i As Integer, j As Integer, t As Integer
Dim ni() As Long, nij() As Long, pij() As Double, newrat As Integer
ReDim nij(1 To classes - 1, 0 To classes), ni(0 To classes)
obs = id.Rows.count
For k = 1 To obs
'Earliest cohort to which observation can belong is from year:
t = Application.Max(ystart, Year(dat(k)))
'Loop through cohorts to which observation k can belong
Do While t < yend
'Is there another rating from the same year?
If id(k + 1) = id(k, 1) And Year(dat(k + 1)) <= t And k <> obs Then
Exit Do
End If
'Is the issuer in default or not rated?
If rat(k) = classes Or rat(k) = 0 Then Exit Do
'Add to number of issuers in cohort
ni(rat(k)) = ni(rat(k)) + 1
'Determine rating from end of next year (=y+1)
'rating stayed constant
If id(k + 1) <> id(k) Or Year(dat(k + 1)) > t + 1 Or k = obs Then
newrat = rat(k)
'rating changed
Else
kn = k + 1
Do While Year(dat(kn + 1)) = Year(dat(kn)) And id(kn + 1) = id(kn)
If rat(kn) = classes Then Exit Do 'Default is absorbing!
kn = kn + 1
Loop
newrat = rat(kn)
End If
'Add to number of transitions
nij(rat(k), newrat) = nij(rat(k), newrat) + 1
'Exit if observation k cannot belong to cohort of y+1
If newrat <> rat(k) Then Exit Do
t = t + 1
Loop
Next k
ReDim pij(1 To classes - 1, 1 To classes + 1)
'Compute transition frequencies pij=Nij/Ni
For i = 1 To classes - 1
For j = 1 To classes
If ni(i) > 0 Then pij(i, j) = nij(i, j) / ni(i)
Next j
Next i
'NR category to the end
For i = 1 To classes - 1
If ni(i) > 0 Then pij(i, classes + 1) = nij(i, 0) / ni(i)
Next i
COHORT = pij
I am very new to SQL Server, can anyone help convert this for SQL? I made an attempt based on searching on internet but it didn't come close:
create table trans as
select a.group as from, b.group as to, count(*) as nTrans
from haveRanks as a inner join haveRanks as b
on a.ID=b.ID and a.Date+1 = b.Date
group by a.group, b.group;
create table probs as
select from, to, nTrans/sum(nTrans) as prob
from trans
group by from;
End Function
My data looks something like this:
ID Date Value
1 1/10/14 5
1 5/10/14 5
1 6/23/16 7
2 3/10/00 12
2 6/10/01 4
Edit: Answering Question from Comments:
1) Correct, if a Highest Rating is not supplied, the program will take the maximum number as the "default" class
2) If there is no rating for the year it is has not changed.
3) Not sure I understand this question, the Do While t < yend loops through the observations and checks if the next observations are in the same cohort, or if it's default/Not Rated it will kick out and go to the next one.

building a 2D array in excel

I'm trying to build an array for a school project, scenario is this:
You have a city that is 30 miles (y) by 20 miles (x) with roads every mile, have to write code that gives the best location for placement of a distribution center based on the business locations and cost to delivery goods to each.
I have one bit of code that records the number of client businesses, an array that records the locations of the businesses, and an array that stores volume of product each client buys.
Where I'm stuck at, is I think I should build an array that is 0 to 30, 0 to 20 (the size of the city) but I have to evaluate the cost based on user defined precision (.25, .5, 1, and 2 miles) so I should have the array be able to store the values from the calculations for 120 by 80 cells.
Not sure if that makes sense, here is the requirements:
Specifically, your program should be able to complete the following tasks:
Read the customer data, and user input for analysis resolution. Your program must be designed to
accommodate changes in the number of customers, their locations, and their product delivery volumes. User options for analysis resolution will be: 0.25 miles, 0.5 miles, 1 mile, and 2 miles.
Validate that user input is numeric and valid.
Analyze the costs at all possible distribution center locations (which may be collocated with customer
locations), and determine the optimums.
Display the X and Y values of the optimum distribution center locations and the corresponding minimum
weekly cost. There may be multiple locations with the same minimum cost.
Display the costs at all locations adjacent to the optimums, in order to show the sensitivity of the result.
The formulas to use are:
Distance to customer (Di)=abs|x-xi|+|y+yi|
Cost for customer (Ci)=1/2*Di*Vi (volume of customer product)* Ft
Ft = 0.03162*y+0.04213*x+0.4462
cost = sum Ci from 1 to number of clients
Below is my code so far, I started it to have it basically build the array and display it on a second sheet, so I can visualize it but I can't have that in the final product. In debugging it, it gets to the line of code di = and gives me a subscript out of range.
Option Explicit
Option Base 1
Sub load()
Dim Cust!, x#, y#, volume#(), n!, loc#(), i%, vol#, xi#, ci#, di#, j#
Dim choices#, val#(), nptsx!, nptsy!, Ft#, lowx!, lowy!, low!, M!
Dim costmatrix#(), npts!, cost!()
'find number of customers
Cust = 0
Do While Cells(8 + Cust, 1).Value <> ""
Cust = Cust + 1
Loop
If Cust < 2 Then
MsgBox "number of customers must be greater than 1."
Exit Sub
End If
'establist array of customer locations
ReDim loc#(1, Cust)
For j = 1 To Cust
x = Cells(7 + j, 2)
y = Cells(7 + j, 3)
Next j
ReDim volume#(Cust, 1)
For i = 1 To Cust
vol = Cells(7 + i, 4)
Next i
choices = Cells(3, 7).Value
nptsx = 30 / choices + 1
nptsy = 20 / choices + 1
'30x20 grid
ReDim costmatrix(x To nptsx, y To nptsy)
For x = 0 To nptsx - 1
Sheet3.Cells(1, x + 2) = x * choices
Next x
For y = 0 To nptsy - 1
Sheet3.Cells(2 + y, 1) = y * choices
Next y
For x = 0 To nptsx - 1
For y = 0 To nptsy - 1
For k = 1 To Cust
di = Abs(x * choices - Sheet1.Cells(7 + j, 2)) + Abs(y * choices - Sheet1.Cells(7 + j, 3))
Ft = 0.03162 * Sheet1.Cells(7 + j, 3) + 0.4213 * Sheet1.Cells(7 + j, 2) + 0.4462
ci = 1 / 2 * di * vol * Ft
Sheet3.Cells(x + 2, 2 + y) = ci
Next k
Next y
Next x
lowx = x
lowy = y
Range("I9:J:3").Clear
Range("I9") = "optimum"
Range("J9") = lowx * choices
Range("K9") = lowy * choices
Range("L9") = low
i = 9
If lowy < npts - 1 Then
i = i + 1
Cells(1, "I") = "Increment North"
Cells(1, "L") = cost(lowx, lowy + 1)
End If
If lowy > 0 Then
i = i + 1
Cells(1, "I") = "Increment South"
Cells(1, "L") = cost(lowx, lowy - 1)
End If
If lowx < npts - 1 Then
i = i + 1
Cells(1, "I") = "Increment East"
Cells(1, "L") = cost(lowx, lowy + 1)
End If
If lowx > 0 Then
i = i + 1
Cells(1, "I") = "Increment West"
Cells(1, "L") = cost(lowx, lowy - 1)
End If
End Sub
Updated, I have built the array, but I need to figure out how to do the calculations for all clients in one cell at a time, adding the results for each client together and putting the sum of them into the cell, then going onto the next cell.
When you dimension loc# via
ReDim loc#(Cust, 2)
The first index must be between 1 and Cust
The you have the loop
For k = 1 To Cust
x = Cells(7 + k, 2)
y = Cells(7 + k, 3)
Next k
After this loop runs k has value Cust + 1, not Cust since for-loops in VBA first increment the counter and then test if it has exceeded the limit.
You don't use k again until the line
di = Abs(Sheet3.Cells(1, x + 2) - loc(k, 1))
At this stage k is Cust + 1 -- which is one more than the highest permissible subscript, hence the subscript out of range error.
In context, I think that you meant to use j rather than k in both that line and the next line. I don't know if your code has other issues, but getting rid of k in those lines should help.

sorting 1d array in VB

I wrote a 1D array sorting code, however the first value disappears after sorting. Here is my code:
For i = 0 To 10 - 1
For j = 0 To (10 - 1) - i
If Xs(j) > Xs(j + 1) Then
tmp = Xs(j)
Xs(j) = Xs(j + 1)
Xs(j + 1) = tmp
End If
Next j
Next i
Original array:
0.995136318967065
1.92659411953677E-02
0.075211466386023
0.276865639306513
0.796949177428061
0.644136557566409
0.912439108707731
0.318021611061513
0.863316048056547
0.469710111256482
Array after sorting:
0
1.92659411953677E-02
0.075211466386023
0.276865639306513
0.318021611061513
0.469710111256482
0.644136557566409
0.796949177428061
0.863316048056547
0.912439108707731
I suspect you have dimensioned your array 0 To 10:
Dim Xs(0 To 10)
so creating 11 spaces into it. However, you have only 10 of them so you will have an Empty cell that will put itself on the first position at some point of the loop (being it evaluated as 0, which is indeed the lowest value into your dataset).
I also believe you have dimensioned your array 0 To 10 instead of 0 To 9 because, if not, you would have got an Subscript out of range error in this part of the code:
For j = 0 To (10 - 1) - i
In order to make your code work:
a) Change the Dim Xs(0 To 10) to Dim Xs(0 To 9)
b) Change the For j = 0 To (10 - 1) - i to For j = 0 To (10 - 1) - i-1

MATLAB: Finding the entry number of the first '1' in a logical array

I have created a logical array of 1's and 0's using the following code:
nWindow = 10;
LowerTotInitial = std(LowerTot(1:nWindow));
UpperTotInitial = std(UpperTot(1:nWindow));
flag = 0;
flagArray = zeros(length(LowerTot), 1);
for n = 1 : nData0 - nWindow
for k = 0 : nWindow - 1
if LowerTot(n + k) < 0.1*LowerTotInitial || UpperTot(n + k) < 0.1*UpperTotInitial
flag = 1;
flagArray(n) = 1;
else
flag = 0;
end
end
end
This returns flagArray, an array of 0's and 1's. I am trying to find the index of the first 1 in the array. ie. 1 = flagArray(index). I am confused as to what is the best way to accomplish this!
What you call an entry number is referred to as an index in MATLAB-speak. To find the index of the first matching element in an array you can use the FIND function:
>> x = [0 0 1 0 1 0];
>> find(x, 1, 'first')
ans =
3
Try this ind = find(flagArray, k, 'first')
with k =1
Read this Matlab Docs - find

Resources