VBA loop works using F8 but not when running free - loops

I realise these errors are unique to the code written so no previous examples have helped much, except I can report that I do trap any errors, and none show up. The procedure is long but here is the part that is being missed out in realtime.
...With rsFacilityStock
.Edit
!TotalShares = !TotalShares + rsPending!Shares
Select Case rsPending!BuySell
Case BUY_STOCK
strTradeType = "BUY"
lngMovementID = MOVEMENT_PURCHASE
Case PARTSELL_STOCK, SELL_STOCK
If rsPending!BuySell = PARTSELL_STOCK Then
strTradeType = "PSALE"
Else
strTradeType = "SALE"
**!Archived = True
!ArchiveDate = rsPending!PurchaseDate**
End If
'Build Array for clearing out sharesleft
intSaleCount = intSaleCount + 1
ReDim Preserve SaleRecord(1 To intSaleCount)
With SaleRecord(intSaleCount)
.FacilityStockID = rsPending!FacilityStockID
.TradeDate = rsPending!PurchaseDate
.SharesTraded = rsPending!Shares
End With
Case 4
strTradeType = "ROLLO"
booCashPot = False
End Select
.Update
End With...
The part between the ** is what fails when the trade is a Sale. I note that the strTradeType does get set but the Archiving fails. My suspicion is that it is the .Update that is failing. Just don't know why. Ideas welcome.

Related

One line of code in Loop gives undesirable results

The code below copies the values of the selected record to all records on my form.
But, this line in the code is giving me undesirable results
.Fields("ResultsID").Value = Me.TestResultID.Value
Instead of copying the TestResultIDs of each record into ResultsID, it makes all ResultsID the same as the selected record's TestResultsID.
Where would be the best place to move that line of code to?
With Me.RecordsetClone
.MoveFirst
Do While .EOF = False
If .Fields("[Ordered Analyte]").Value = Me.[Ordered Analyte].Value Then
.Edit
.Fields("DateStarted").Value = Me.DateStarted.Value
.Fields("TimeStarted").Value = Me.TimeStarted.Value
.Fields("DateCompleted").Value = Me.DateCompleted.Value
.Fields("TimeCompleted").Value = Me.TimeCompleted.Value
.Fields("Result").Value = Me.Result.Value
.Fields("Count").Value = Me.[txtCount].Value
.Fields("ResultsID").Value = Me.TestResultID.Value
.Update
End If
.MoveNext
Loop
End With
replace
.Fields("ResultsID").Value = Me.TestResultID.Value
with
.Fields("ResultsID").Value = .Fields("TestResultsID").Value
to use the TestResultsID from each individual record instead of just the current one.
The code below copies the values of the selected record to all records
on my form.
and:
it makes all ResultsID the same as the selected record's TestResultsID.
Thus, your code works exactly as intended.

how to for each loop on data table within another datatable

I have a web poll application that reads and processes orders from sql server back end and inserts into windss(jda).
the flow
1) I read all the orders from the sql server tables that is not processed
2) then I need to divide the orders into two sets
- set 1 orders with bundle kit( 1 order with several suborders)
- set 2 is just orders with no bundle kit
3) then after each order is processed I need to update the isprocessed sql field to 1
1) code for reading all orders
Frmmain.vb
dt = WebDatabase.GetAllOrdersFromDatabase()**'this method is below**
For Each drow In dt.Rows
If CDbl(WinDSSStoreNumber) = 123 Or CDbl(WinDSSStoreNumber) = 124 Then
' Store 123 and 124 = customer service - only orders with qualifying source codes
my question is:
the above for each checks if the store is 123 or 124 but now I want to implement another for each loop that reads all the InvoiceHeader_Id that the second field in the datatable and then check if it has a bundle kit or not if it does then process it and update the isprocessed field second last in the datatable else process the orders without any bundle kit and update isprocessed for those as well. please any help is generously appreciated, please ask me any questions in the below comment before marking my question down.
WebData.vb
Public Function GetAllOrdersFromDatabase() As DataTable
DrivePath = "C:\Users\somjething\Documents\files\somefiles\"
Dim ds As DataTable = Nothing
WinDSS.connectionString = ConfigurationManager.AppSettings("WinDSS_Connection").Replace("%DrivePath%", DrivePath)
ds = WinDSS.GetSysMst()
If ds.Rows.Count > 0 Then
WinDSSStoreNumber = ds.Rows(0)("store_no")
End If
Dim dt As New DataTable()
Dim conn As New SqlConnection(ConfigurationManager.AppSettings("WebData_Connection") & ConfigurationManager.AppSettings("WebDataSource"))
Dim cmd As SqlCommand
Dim da As New SqlDataAdapter
conn.Open()
cmd = conn.CreateCommand()
cmd.CommandType = CommandType.Text
cmd.CommandText= SELECT InvoiceDetail_Id, InvoiceHeader_Id, ActualFreightCharge, AmountCollected,
ChargedActualFreight, CollectedExternally, CollectedThroughAR, DateInvoiced, InvoiceNo,
InvoiceType, LineSubTotal, MasterInvoiceNo, OrderInvoiceKey, Reference1, TotalAmount,
TotalTax, isprocessed, storetoprocess
FROM dbo.InvoiceHeader
WHERE (isprocessed = 0) AND (storetoprocess = N'123')
da.SelectCommand = cmd
da.Fill(dt)
conn.Close()
Return dt
End Function
Additoinal info
This is the information given to me by my manager:
loop throught each below
SELECT InvoiceDetail_Id, InvoiceHeader_Id, ActualFreightCharge, AmountCollected,
ChargedActualFreight, CollectedExternally, CollectedThroughAR, DateInvoiced, InvoiceNo,
InvoiceType, LineSubTotal, MasterInvoiceNo, OrderInvoiceKey, Reference1, TotalAmount,
TotalTax, isprocessed, storetoprocess
FROM dbo.InvoiceHeader WHERE (isprocessed = 0) AND (storetoprocess = N'195')
Use the above InvoiceHeader_Id to loop throught all of the order information. Process each Bundle (Kit/)
SELECT InvoiceHeader_Id, LineDetails_Id, LineDetail_Id, OrderLine_Id, GiftFlag, [References],
GiftWrap, IsBundleParent, KitCode, KitQty, LevelOfService, LineSeqNo, LineType,
MaxLineStatus, MaxLineStatusDesc, MinLineStatus, MinLineStatusDesc, MinShipByDate,
OpenQty, OrderHeaderKey, OrderLineKey, OrderedQty, OriginalOrderedQty, OtherCharges,
OverallStatus, PipelineKey, PrimeLineNo, ReceivingNode, RemainingQty, ReqCancelDate,
ReqDeliveryDate,
ReqShipDate, SCAC, ScacAndService, ScacAndServiceKey, ShipNode, ShipToID, ShipToKey,
StatusQuantity, SubLineNo, SubstituteItemID, isprocessed
FROM dbo.OrderLine
WHERE (isprocessed = 0) AND (InvoiceHeader_Id = 13) AND (IsBundleParent = 'Y')
ORDER BY PrimeLineNo, SubLineNo
For each record in the above list query below and add as Zero (0) dollar amount. The cost is associated with the information above record (you may have to query tables to ge the values)
Get the OrderLineKey from the above record and query this below to get the associated sub items.
SELECT TOP (100) PERCENT dbo.BundleParentLine.InvoiceHeader_Id AS BPL_InvoiceHeader_Id,
dbo.BundleParentLine.LineDetails_Id AS BPL_LineDetails_Id, dbo.BundleParentLine.LineDetail_Id AS BPL_LineDetail_Id, dbo.BundleParentLine.OrderLine_Id AS BPL_OrderLine_Id, dbo.BundleParentLine.BundleParentLine_id, dbo.BundleParentLine.SubLineNo AS BPL_SubLineNo, dbo.BundleParentLine.PrimeLineNo AS BPL_PrimeLineNo, dbo.BundleParentLine.OrderLineKey AS BPL_OrderLineKey, dbo.OrderLine.*
FROM dbo.BundleParentLine INNER JOIN dbo.OrderLine ON dbo.BundleParentLine.OrderLine_Id = dbo.OrderLine.OrderLine_Id AND dbo.BundleParentLine.LineDetail_Id = dbo.OrderLine.LineDetail_Id AND dbo.BundleParentLine.LineDetails_Id = dbo.OrderLine.LineDetails_Id AND dbo.BundleParentLine.InvoiceHeader_Id = dbo.OrderLine.InvoiceHeader_Id
WHERE (dbo.BundleParentLine.OrderLineKey = N'76873264832') AND (dbo.BundleParentLine.InvoiceHeader_Id = 13) AND (dbo.BundleParentLine.LineDetails_Id = 6) AND (dbo.OrderLine.isprocessed = 0)
ORDER BY BPL_PrimeLineNo, BPL_SubLineNo
After Processed, set isprocessed = 1
Use the above InvoiceHeader_Id to loop throught all of the order information
SELECT InvoiceHeader_Id, LineDetails_Id, LineDetail_Id, OrderLine_Id, GiftFlag, [References],
GiftWrap, IsBundleParent, KitCode, KitQty, LevelOfService, LineSeqNo,
LineType,
MaxLineStatus, MaxLineStatusDesc, MinLineStatus, MinLineStatusDesc, MinShipByDate,
OpenQty, OrderHeaderKey, OrderLineKey, OrderedQty,
OriginalOrderedQty,
OtherCharges, OverallStatus, PipelineKey, PrimeLineNo, ReceivingNode, RemainingQty,
ReqCancelDate, ReqDeliveryDate, ReqShipDate, SCAC,
ScacAndService,
ScacAndServiceKey, ShipNode, ShipToID, ShipToKey, StatusQuantity,
SubLineNo, SubstituteItemID, isprocessed
FROM dbo.OrderLine
WHERE (isprocessed = 0) AND (InvoiceHeader_Id = 13) AND (IsBundleParent <> 'Y')
ORDER BY PrimeLineNo, SubLineNo
After Processed, set isprocessed = 1
This is not an answer but I want to pose this to prompt you for some clarification and it's not practical in the comments.
First, close visual studio and open SQL Server Management Studio and connect to the database
We'll build some select statements to get the data back and then we can think about an UPDATE statement
This first query you posted gives you the unprocessed headers for store 195 (straight from your post). I don't know if you want to do this for all stores or not. Paste it into SSMS and run it
SELECT H.*
FROM dbo.InvoiceHeader H
WHERE H.isprocessed = 0 AND H.storetoprocess = N'195'
Now, this second query gives you the unprocessed lines against that header that have IsBundleParent='Y'.
Look! No loops!
SELECT H.*, L.*
FROM dbo.InvoiceHeader H
INNER JOIN
dbo.OrderLine L
ON L.InvoiceHeader_Id = H.InvoiceHeader_Id
WHERE H.isprocessed = 0 AND H.storetoprocess = N'195'
AND L.isprocessed = 0 AND L.IsBundleParent = 'Y'
Then in your explanation you have For each record in the above list query below and add as Zero (0) dollar amount which makes no sense to me so perhaps you could clarify
Now we'll add the third query in which adds BundleParentLine (which does have inner joins in it already, but it's a pretty strange list of join fields)
SELECT H.*, L.*, BPL.*
FROM dbo.InvoiceHeader H
INNER JOIN
dbo.OrderLine L
ON L.InvoiceHeader_Id = H.InvoiceHeader_Id
INNER JOIN
dbo.BundleParentLine BPL
ON BPL.OrderLine_Id = L.OrderLine_Id
AND BPL.LineDetail_Id = L.LineDetail_Id
AND BPL.LineDetails_Id = L.LineDetails_Id
AND BPL.InvoiceHeader_Id = L.InvoiceHeader_Id
WHERE H.isprocessed = 0 AND H.storetoprocess = N'195'
AND L.isprocessed = 0 AND L.IsBundleParent = 'Y'
Then in your explanation you have After Processed, set isprocessed = 1, but what is 'processed' here? Is it just setting it to processed in the table?
To do that you just write an UPDATE statement. Here's one way to do that to update just the header (don't run it though until we understand what you're trying to do). Is the problem here that you want to set header and line to processed at the same time?
UPDATE InvoiceHeader
SET Processed = 1
WHERE isprocessed = 0 AND storetoprocess = N'195'
The fourth query you have seems to account for the IsBundleParent <> 'Y' case
Again, we need to know what add as Zero (0) dollar amount and processed means to go any further.

VBA: avoid empty cells when creating array from pivottable

I'm trying to create an array based on a pivot table with multiple empty cells, however instead of referring to previous value, the array keeps all the empty cells:
For AllCostTypeRowCounter = 1 To SiteRowCount
AllCostTypeArrayCounter = AllCostTypeArrayCounter + 1
ReDim Preserve AllCostTypeArray(2, AllCostTypeArrayCounter)
If Not CountryRange(AllCostTypeRowCounter, 1) Is Nothing Then
AllCostTypeArray(1, AllCostTypeArrayCounter) = CountryRange(AllCostTypeRowCounter, 1)
Else
AllCostTypeArray(1, AllCostTypeArrayCounter) = AllCostTypeArray(1, AllCostTypeArrayCounter - 1)
End If
AllCostTypeArray(2, AllCostTypeArrayCounter) = SiteRange(AllCostTypeRowCounter, 1).Value
Next AllCostTypeRowCounter
Nvm I solved the question by changing the following code:
If Not CountryRange(AllCostTypeRowCounter, 1) Is Nothing Then
to:
If CountryRange(AllCostTypeRowCounter, 1) <> "" Then
Can anyone tell me why this change works. The above seems the same to me. Also how do I close my own post?

VB.Net : Create a Recordset with manual inputs and GetRows() methods failing

First time writing on a forum but this one really left me no choice and it seems that nobody had the same problem as I have... not a good sign...
I have a project to use the COM Server of a software we use internally and need to use one of their built-in function which requires a recordset as an input and return another recordset with the results (important because I need to stick with the recordset).
Here's breifly what I tried. I create a recordset from scratch and fill it with some hardcoded data just for testing purposes. Once my recordset is filled, I want to look at the data just to be sure everything works well, but I'll have to do the same eventually with my results.
The problem I get is it seems that the GetRows() method return only 1 row every time depending on the last row I moved to. But once it's called, I cannot get the other records. I'm already using the GetRows() method with an actual query and still with an ADODB recordset and it works perfectly. Building a recodset from scratch seems less easy.
I need to put all my data in an object to work with it. But even if I want to use only a recordset, I cannot access to all data in it. Very fustrating... something I'm missing here...
Error I get: either bof or eof is true or the current record has been deleted
Thanks in advance,
Public Function GetFDBData() As Boolean
Dim filtersView As New ADODB.Recordset
Dim rsFields(1) As Object
Dim fieldsAPT(3, 1) As Object
Dim dataView As Object
Dim i As Integer
rsFields(0) = "Field Name"
rsFields(1) = "Filter"
fieldsAPT(0, 0) = "ISIN"
fieldsAPT(0, 1) = "=CA89*"
fieldsAPT(1, 0) = "Currency"
fieldsAPT(1, 1) = "=CAD"
fieldsAPT(2, 0) = "Line"
fieldsAPT(2, 1) = "=Bond"
fieldsAPT(3, 0) = "Redemption Date"
fieldsAPT(3, 1) = "=20230*"
Try
'Build the recordset containing APT fields and filters (in the same variable fieldsAPT)
filtersView.CursorLocation = ADODB.CursorLocationEnum.adUseClient
filtersView.Fields.Append(rsFields(0), ADODB.DataTypeEnum.adVarChar, 30)
filtersView.Fields.Append(rsFields(1), ADODB.DataTypeEnum.adVarChar, 30)
filtersView.Open(, , ADODB.CursorTypeEnum.adOpenStatic, ADODB.LockTypeEnum.adLockOptimistic)
Dim fieldAPT(1)
For i = 0 To UBound(fieldsAPT)
fieldAPT(0) = fieldsAPT(i, 0)
Console.WriteLine(fieldAPT(0)) 'Works fine
fieldAPT(1) = fieldsAPT(i, 1)
Console.WriteLine(fieldAPT(1)) 'Works fine
filtersView.AddNew(rsFields, fieldAPT)
filtersView.Update()
Console.WriteLine(filtersView.RecordCount) 'I can see 1 2 3 4 no problem here
Next i
Dim xx As Integer = filtersView.RecordCount 'xx is 4 as expected
Console.WriteLine("xx: " & xx)
filtersView.MoveFirst() 'Will move to the first record or whatever record
'dataView = filtersView.GetRows() 'I expected this line to work, but same results
For i = 0 To xx - 1
dataView = filtersView.GetRows()
Console.WriteLine(dataView(i, 0).ToString) 'ISIN, normal
Console.WriteLine(filtersView.RecordCount) 'Still equals 4, normal
Console.WriteLine(filtersView.BOF) 'False, normal
Console.WriteLine(filtersView.EOF) 'True, which is NOT normal
Console.WriteLine(filtersView.AbsolutePosition) 'Get -3 not sure why (position 1 related to 4???)
Console.WriteLine(filtersView.MaxRecords) 'Get 0 not sure why
filtersView.MoveNext() '!!!! Here is where it fails !!!! Cannot go more than i=0
Next i
GetFDBData = True
Catch ex As Exception
MsgBox(ex.Message)
GetFDBData = False
Finally
'Clear memory
filtersView.Close()
End Try
End Function
Also, if I do this,
Dim xx As Integer = filtersView.RecordCount 'xx is 4 as expected
Console.WriteLine("xx: " & xx)
filtersView.MoveLast()
Instead of
Dim xx As Integer = filtersView.RecordCount 'xx is 4 as expected
Console.WriteLine("xx: " & xx)
filtersView.MoveFirst()
It will return "Redemption date" in the for loop after. Which makes sense because it is the last record. But puting movefirst even after does'nt solve the issue... still one row only. So the data is there, but I really can't extract one line and one line only...
Try changing your cursor type to adOpenDynamic
EDIT: OK,your line
dataView = filtersView.GetRows()
is causing your cursor to travel to the end of the recordset, try moving it outside your loop and following it with a new MoveFirst like so
filtersView.MoveFirst() 'Will move to the first record or whatever record
'dataView = filtersView.GetRows() 'I expected this line to work, but same results
dataView = filtersView.GetRows()
filtersView.MoveFirst()
Dim sTemp As String = ""
For i = 0 To xx - 1
'Console.WriteLine(dataView(i, 0).ToString) 'ISIN, normal
Console.WriteLine(filtersView.RecordCount) 'Still equals 4, normal
Console.WriteLine(filtersView.BOF) 'False, normal
Console.WriteLine(filtersView.EOF) 'True, which is NOT normal
Console.WriteLine(filtersView.AbsolutePosition) 'Get -3 not sure why (position 1 related to 4???)
Console.WriteLine(filtersView.MaxRecords) 'Get 0 not sure why
sTemp = sTemp & "(" & dataView(0, i).ToString & ", " & dataView(1, i).ToString & ")"
filtersView.MoveNext() '!!!! Here is where it fails !!!! Cannot go more than i=0
Next i
Console.WriteLine(sTemp)
You can verify that by checking the value of filtersView.AbsolutePosition immediately before and after your call to GetRows
Also, you are reversing rows and columns in dataView, move i to the second subscript position. I put it in a temporary string to make it easier to view in the debugger.

Not sure how to approch this, doing some math with error checking and updating my new value in tsql

if (freightCostTotal == 0)
{
freightCount = 1;
dataGridView1.Rows[i].Cells[iFreightCount].Value = "1";
if (freightCostDefinedTotal != 0)
{
freightCostTotal = Convert.ToDecimal(pcsg.Freight_CountColumn.Table.Rows[0]["Fixed Freight"].ToString());
}
else
{
if (!String.IsNullOrEmpty(dataGridView1.Rows[i].Cells[iCost_Prior_ReCompute].Value.ToString()))
Cost_Prior_ReCompute = Convert.ToDecimal(dataGridView1.Rows[i].Cells[iCost_Prior_ReCompute].Value.ToString());
//freightCostPercentTotal = 0.05M;
//decimal costFreight = Convert.ToDecimal(pcsg.Freight_CountColumn.Table.Rows[0]["Cost"].ToString());
freightCostTotal = (Cost_Prior_ReCompute * freight_perc_);
}
dataGridView1.Rows[i].Cells[iFreight].Value = String.Format("{0:0.00}", freightCostTotal);
}
The following is not working. This is my first attempt at doing sql math
select freightCostTotal, Cost_Prior_ReCompute],freight_perc_, FixedFreight,
if (freightCostTotal == 0) then freightCount = 1;
if (freightCostDefinedTotal != 0) then freightCostDefinedTotal = FixedFreight else
set freightCostTotal = (Cost_Prior_ReCompute * freight_perc_);
from VF_CasINV_Cost
Thanks,
Jerry
Not sure what you're after exactly, but here's a start below. FYI -- your conditional on Cost_Prior_Recompute needs a default / else value -- I just put a '?' in there for now, since I can't tell what it should be.
Also -- I can't tell if freigntCostTotal is an actually field in your database that you're trying to update, or if you plan to just compute it based on other fields each time. So far, I'm assuming you're just going to compute it.
So this is how you would select -- keeping in mind (I assume from reading your code) you are looking for data where the frieghtCostTotal has NOT been updated in the database yet.
SELECT
1 as freightCount,
CASE WHEN freightCostDefinedTotal <> 0
THEN FixedFreight
ELSE ISNULL(Cost_Prior_ReCompute,?) * freight_perc_
END as freigntCostTotal,
Cost_Prior_ReCompute,
freight_perc_,
FixedFreight
FROM
VF_CasINV_Cost
WHERE
freightCostTotal = 0
Alternatively, you could just pull the data out like this, but it will get all data, not just the freightCostTotal = 0 data.
SELECT
1 as freightCount,
freigntCostTotal,
Cost_Prior_ReCompute,
freight_perc_,
FixedFreight
FROM
VF_CasINV_Cost
Here's how you would update. BTW -- If you're new to updating with SQL, I'd highly recommend you test this out on some non-production data first. Or at least, back-up your table first.
UPDATE VF_CasINV_Cost
SET freightCostTotal = CASE WHEN freightCostDefinedTotal <> 0
THEN FixedFreight
ELSE ISNULL(Cost_Prior_ReCompute,?) * freight_perc_
END
WHERE freightCostTotal = 0

Resources