DataTable select rows where debit and credits match - wpf

Where a DataTable has the following Columns
Account Number (Integer) (Unique)
Debit (Decimal)
Credit (Decimal)
Selected (Boolean)
There may be several rows with the same account number and either a Debit Entry or a Credit Entry. What I am attempting to do is match up the debits and credits where they add up to the same value and mark them as selected by iterating through all the rows. Any idea on the best method to achieve this?
Thanks
e.g.
SQL
strSQL = "SELECT A_Sales_Ledger.Transaction_ID as 'Transaction', "
strSQL += "Customers.Cust_No as 'Acct', "
strSQL += "Customers.Cust_Name as 'Name', "
strSQL += "Customers.Add1 as 'Unit', "
strSQL += "A_Sales_Ledger.Debit as 'Debit', "
strSQL += "A_Sales_Ledger.Credit as 'Credit', "
strSQL += "A_Sales_Ledger.Document_Date as 'Date', "
strSQL += "A_Sales_Ledger.S_Description as 'Description' "
strSQL += "FROM A_Sales_Ledger "
strSQL += "JOIN Customers ON Customers.Customer_ID = A_Sales_Ledger.Customer_ID "
strSQL += "WHERE A_Sales_Ledger.Paid = 'N' "
strSQL += "ORDER BY Customers.Cust_No"

This may not be the best solution but it does seem to work...
I'm making three passes though the DataTable
Pass one - if the total of the debits equals the total of the credits for each customer mark them as selected
Pass two - Add the total of the credits for the customer and iterate though the debits until the same value is achieved and mark them as selected
Pass three - mop up any remaining credit entries that match a debit entry for the same customer...
For Each Row As DataRow In BalanceDT.Rows
Dim vAcct As String = Row("Acct")
Dim vDebits As Decimal = BalanceDT.Compute("SUM(Debit)", "Acct = '" & vAcct & "'")
Dim vCredits As Decimal = BalanceDT.Compute("SUM(Credit)", "Acct = '" & vAcct & "'")
If vDebits = vCredits Then
Row("Selected") = True
End If
Next
Dim CurrentCust As String = ""
Dim TransactionDT As New DataTable
Dim ExitFor As Boolean = False
With TransactionDT.Columns
.Add("ID", GetType(Integer))
End With
For Each Row As DataRow In BalanceDT.Rows
Dim vAcct As String = Row("Acct")
ExitFor = False
TransactionDT.Rows.Clear()
If Not CurrentCust = vAcct Then
Dim vCredits As Decimal = BalanceDT.Compute("SUM(Credit)", "Acct = '" & vAcct & "'")
Dim vSelected() As DataRow = BalanceDT.Select("Acct = '" & vAcct & "'", Nothing)
For Each SubRow As DataRow In vSelected
If SubRow("Selected") = False Then
vCredits -= SubRow("Debit")
With TransactionDT.Rows
.Add(SubRow("Transaction"))
End With
If vCredits = 0 Then
ExitFor = True
Exit For
End If
End If
Next
If ExitFor = True Then
For Each SubRow As DataRow In vSelected
If SubRow("Credit") > 0 Then
SubRow("Selected") = True
End If
If SubRow("Debit") > 0 Then
For Each CustomerRow As DataRow In TransactionDT.Rows
If CustomerRow("ID") = SubRow("Transaction") Then
SubRow("Selected") = True
End If
Next
End If
Next
End If
End If
CurrentCust = vAcct
Next
For Each Row As DataRow In BalanceDT.Rows
Dim vAcct As String = Row("Acct")
If Not CurrentCust = vAcct Then
Dim vSelected() As DataRow = BalanceDT.Select("Acct = '" & vAcct & "' AND Selected = 'False'", "Credit")
For Each SubRow As DataRow In vSelected
If SubRow("Selected") = False Then
Dim vCredit As Decimal = SubRow("Credit")
For Each CustomerRow In vSelected
If CustomerRow("Selected") = False Then
Dim vDebit As Decimal = CustomerRow("Debit")
If Not vDebit = 0 And Not vCredit = 0 Then
If vDebit = vCredit Then
With TransactionDT.Rows
CustomerRow("Selected") = True
SubRow("Selected") = True
End With
Exit For
End If
End If
End If
Next
End If
Next
End If
CurrentCust = vAcct
Next

Related

Creating Lookup based on user defined ranges

I'm certain I am overlooking something simple but I just can't figure it this morning. I am attempting to simulate a XLookup for users with VBA code. Folks I work with have a range of excel skills and some just have a really hard time with this formula.
My code prompts the users to define all relevant ranges but when the lookup itself is returning Error 9.
Sub Lookup()
Dim invRange, lkRange, rtnRange, outRange As Range
Dim strInput, invPrompt, invTitle, lkPrompt, lkTitle, rtnPrompt, rtnTitle, outPrompt, outTitle As String
Dim invArray, lkArray, rtnArray, outArray As Variant
Dim x, j, i, k As Integer
Dim txt As String
ReDim invRange(1 To 1, 1 To 1)
invPrompt = "Select the Invoices you wish to look up."
invTitle = "Select Lookup Value"
lkPrompt = "Select the column where you wish to lookup the Invoices."
lkTitle = "Select Lookup Range"
rtnPrompt = "Select the column where you wish to return data from."
rtnTitle = "Select Return Range"
outPrompt = "Select the column where you wish to output the data."
outTitle = "Select Output Range"
On Error Resume Next
' Invoice Range Selection Input Box
Set invRange = Application.InputBox( _
Prompt:=invPrompt, _
Title:=invTitle, _
Default:=Selection.Address, _
Type:=8) 'Range selection
If invRange Is Nothing Then Exit Sub
' Turns Range into Array or Exits sub if no range was selected
invArray = Application.Transpose(invRange.Value)
If IsArray(invArray) = False Then
invArray = Array(invArray)
End If
For x = 0 To UBound(invArray)
invArray(x) = Replace(invArray(x), Chr(160), " ")
invArray(x) = RTrim(invArray(x))
Next
' Lookup Range Selection Input Box
Set lkRange = Application.InputBox( _
Prompt:=lkPrompt, _
Title:=lkTitle, _
Default:=Selection.Address, _
Type:=8) 'Range selection
If lkRange Is Nothing Then Exit Sub
' Turns Range into Array or Exits sub if no range was selected
lkArray = Application.Transpose(lkRange.Value)
If IsArray(lkArray) = False Then
lkArray = Array(lkArray)
End If
For j = 0 To UBound(lkArray)
lkArray(j) = Replace(lkArray(j), Chr(160), " ")
lkArray(j) = RTrim(lkArray(j))
Next
' Return Range Selection Input Box
Set rtnRange = Application.InputBox( _
Prompt:=rtnPrompt, _
Title:=rtnTitle, _
Default:=Selection.Address, _
Type:=8) 'Range selection
If rtnRange Is Nothing Then Exit Sub
' Turns Range into Array or Exits sub if no range was selected
rtnArray = Application.Transpose(rtnRange.Value)
If IsArray(rtnArray) = False Then
rtnArray = Array(rtnArray)
End If
For i = 0 To UBound(rtnArray)
rtnArray(i) = Replace(rtnArray(i), Chr(160), " ")
rtnArray(i) = RTrim(rtnArray(i))
Next
' Output Range Selection Input Box
Set outRange = Application.InputBox( _
Prompt:=outPrompt, _
Title:=outTitle, _
Default:=Selection.Address, _
Type:=8) 'Range selection
If outRange Is Nothing Then Exit Sub
' Turns Range into Array or Exits sub if no range was selected
outArray = Application.Transpose(outRange.Value)
If IsArray(outArray) = False Then
outArray = Array(outArray)
End If
For k = 0 To UBound(outArray)
outArray(k) = Replace(outArray(k), Chr(160), " ")
outArray(k) = RTrim(outArray(k))
Next
On Error GoTo 0
'Lookup each item from LookupValue array
For i = 1 To UBound(invArray)
For j = 1 To UBound(lkArray)
If invArray(i, 1) = lkArray(j, 1) Then
outArray(i, 1) = rtnArray(j, 1)
Exit For
End If
Next j
Next i
outArray.Resize(UBound(outArray, 1), 1).Value = outArray
End Sub

Remove delimiters from Join() Function in EXcel VBA

I am a novice programmer and I'm building a form via VBA for excel where the user will input employee's time sheet and their initials via 16 text box's in the form. The text boxes data are stored to a string array. The code is:
Dim initials(15) As String
initials(0) = TB_Initials_1
initials(1) = TB_Initials_2
initials(2) = TB_Initials_3
...
initials(15) = TB_Initials_15
After using the find function and referencing some data from a one excel sheet, I use
ActiveCell.Offset(0, 2).Value = Join(initials, ".")
to output the following
"js.rs.............." to the active cell in a different excel sheet, (I only entered 2 of the 16 input boxes, hence there's two initials. JS.RS
The trailing .............. is what I want to remove. this will be imported into a Database later via the excel sheet.
How can I remove the xtras ".........'s at the end of the string? I have tried the "Trim()" function, but that does not work in my case. Everything i've tried online does not seem to work either or is referencing items from a work book, not a text box.
Any help is appreciated.
The entire code is below:
Option Explicit
'Variable declaration
Dim startTime(15), endTime(15), ST_Finish_Date As Date
Dim totalmin(15), Total_min, Total_Cost, Rate(15), Line_cost(15), Cost_Per_Part As String
Dim initials(15) As String
Dim i, ii As Integer
Dim Found_ini(15) As Range
Dim Found As Range 'returned value from find
Dim TBtraveller_value As String 'text box traveller value
Dim Found2 As Range 'store part code range
Dim TBDESC As Range ' Returned value from 2nd search
Dim BL_Find_Check As Boolean
Private Sub CB_Write_Click()
create_csv
End Sub
Private Sub Close_Form_Click()
Unload Traveller_Entry
End Sub
'still need to make this for every start / stop time text box.
Private Sub TB_Time_Start_1_BeforeUpdate(ByVal Cancel As MSForms.ReturnBoolean)
Dim myvar As String
If Not Me.TB_Time_Start_1 Like "??:??" Then
MsgBox "Please use format 'HH:MM'"
Cancel = True
Exit Sub
End If
myvar = Format(Me.TB_Time_Start_1, "hh:mm")
Me.TB_Time_Start_1 = myvar
End Sub
Public Sub travellerNUM_TextBox_Exit(ByVal Cancel As MSForms.ReturnBoolean)
Workbooks("Traveller entryxlsm.xlsm").Activate
TBtraveller_value = travellerNUM_TextBox.Value
If TBtraveller_value = "" Then
MsgBox ("Enter a Shop Traveller Number!")
Exit Sub
Else
TBtraveller_value = travellerNUM_TextBox.Value
Set Found = Sheets("woss").Range("A:A").Find(what:=TBtraveller_value, lookat:=xlWhole)
If Found Is Nothing Then
MsgBox (TBtraveller_value & " Not Found!")
Exit Sub
Else
Part_Code_BOX.Value = Found.Offset(0, 1) 'enters the info into the Part Code Box.
Set Found2 = Found.Offset(0, 1)
End If
If Part_Code_BOX = "" Then
MsgBox ("Traveller number " & TBtraveller_value & " has no part code associated with it." & vbCrLf & "Check Work Order Spread Sheet is FULLY Complete.")
BL_Find_Check = True
Exit Sub
End If
Set TBDESC = Sheets("ProductList").Range("B:B").Find(what:=Found2, lookat:=xlPart)
If TBDESC Is Nothing Then
MsgBox (" Dscription Not Found!")
Else
Desc_Box = TBDESC.Offset(0, 1) 'enters the description into the description Box.
FinishDate_Box = Found.Offset(0, 8) 'enters the finish date into the finish date Box.
Employee = Found.Offset(0, 2) 'enters the Employee name into the employee name Box.
End If
End If
End Sub
Public Sub CB_POST_Click()
On Error Resume Next
startTime(0) = TB_Time_Start_1.Value
startTime(1) = TB_Time_Start_2.Value
startTime(2) = TB_Time_Start_3.Value
startTime(3) = TB_Time_Start_4.Value
startTime(4) = TB_Time_Start_5.Value
startTime(5) = TB_Time_Start_6.Value
startTime(6) = TB_Time_Start_7.Value
startTime(7) = TB_Time_Start_8.Value
startTime(8) = TB_Time_Start_9.Value
startTime(9) = TB_Time_Start_10.Value
startTime(10) = TB_Time_Start_11.Value
startTime(11) = TB_Time_Start_12.Value
startTime(12) = TB_Time_Start_13.Value
startTime(13) = TB_Time_Start_14.Value
startTime(14) = TB_Time_Start_15.Value
startTime(15) = TB_Time_Start_16.Value
endTime(0) = TB_Time_Stop_1.Value
endTime(1) = TB_Time_Stop_2.Value
endTime(2) = TB_Time_Stop_3.Value
endTime(3) = TB_Time_Stop_4.Value
endTime(4) = TB_Time_Stop_5.Value
endTime(5) = TB_Time_Stop_6.Value
endTime(6) = TB_Time_Stop_7.Value
endTime(7) = TB_Time_Stop_8.Value
endTime(8) = TB_Time_Stop_9.Value
endTime(9) = TB_Time_Stop_10.Value
endTime(10) = TB_Time_Stop_11.Value
endTime(11) = TB_Time_Stop_12.Value
endTime(12) = TB_Time_Stop_13.Value
endTime(13) = TB_Time_Stop_14.Value
endTime(14) = TB_Time_Stop_15.Value
endTime(15) = TB_Time_Stop_16.Value
initials(0) = TB_Initials_1
initials(1) = TB_Initials_2
initials(2) = TB_Initials_3
initials(3) = TB_Initials_4
initials(4) = TB_Initials_5
initials(5) = TB_Initials_6
initials(6) = TB_Initials_7
initials(7) = TB_Initials_8
initials(8) = TB_Initials_9
initials(9) = TB_Initials_10
initials(10) = TB_Initials_11
initials(11) = TB_Initials_12
initials(12) = TB_Initials_13
initials(13) = TB_Initials_14
initials(14) = TB_Initials_15
initials(15) = TB_Initials_16
For i = LBound(initials) To UBound(initials)
Set Found_ini(i) = Sheets("rate").Range("B:B").Find(what:=initials(i), lookat:=xlWhole)
Rate(i) = Found_ini(i).Offset(0, 1) 'finds rate for given initials
totalmin(i) = DateDiff("N", startTime(i), endTime(i))
If Found_ini(i) Is Nothing Then
MsgBox (initials(i) & " Not Found! Update Employee Database.")
Exit Sub
'If IsEmpty(Found_ini(i)) = False And IsEmpty(startTime(i)) = True And IsEmpty(endTime(i)) = True Then
'MsgBox "Enter Some Initials, None Found"
Exit Sub
End If
Next
For ii = LBound(totalmin) To UBound(totalmin)
Line_cost(ii) = totalmin(ii) / 60 * Rate(ii)
Next
Total_min = Application.WorksheetFunction.Sum(totalmin)
Total_Cost = Application.WorksheetFunction.Sum(Line_cost)
Cost_Per_Part = Total_Cost / TextBOX_QTYBUILT
If Total_min = 0 Then
MsgBox (" Enter Some Time!")
ElseIf Total_min < 0 Then
MsgBox ("Time is NEGATIVE. Check Entered Times.")
End If
If BL_Find_Check = False Then
MsgBox "The number of minutes between two Times : " & Total_min & vbNewLine & "total cost: " & Total_Cost _
& vbNewLine & "cost Per Part " & Cost_Per_Part, vbInformation, "Minutes Between Two Times"
Sheets("test").Select
Range("A1048576").Select
ActiveCell.End(xlUp).Select
ActiveCell.Offset(1, 0).Select
ActiveCell.Offset(0, 0).Value = FinishDate_Box 'Traveller finish Date
ActiveCell.Offset(0, 1).Value = TBtraveller_value 'Traveller Number
ActiveCell.Offset(0, 2).Value = Join(initials, ".") 'Traveller Employee Given to
ActiveCell.Offset(0, 3).Value = Part_Code_BOX.Value ' part number
ActiveCell.Offset(0, 4).Value = Total_Cost ' traveller total cost
ActiveCell.Offset(0, 5).Value = Cost_Per_Part 'Traveller cost per part
End If
End Sub
Sub create_csv()
Dim FileName As String
Dim PathName As String
Dim ws As Worksheet
Set ws = ActiveWorkbook.Sheets("test")
FileName = "CSV_Output_R1.csv"
PathName = Application.ActiveWorkbook.Path
ws.Copy
ActiveWorkbook.SaveAs FileName:=PathName & "\" & FileName, _
FileFormat:=xlCSV, CreateBackup:=False
End Sub
Thank you,
You can use WorksheetFunction.TextJoin() in Excel2019+ in one string:
ActiveCell.Offset(0, 2).Value = WorksheetFunction.TextJoin(".", True, initials)
A small example for comparison:
Sub test1()
Dim arr(1 To 15)
For i = 1 To 15
arr(i) = IIf(Rnd() > 0.7, "TXT", "")
Next
Debug.Print "With Join(): " & Join(arr, ".")
Debug.Print "With TextJoin(): " & WorksheetFunction.TextJoin(".", True, arr)
End Sub
Output
With Join(): ..TXT........TXT..TXT..
With TextJoin(): TXT.TXT.TXT
Here is a function that I just made to trim empty elements off the end of your array:
Function TrimArray(ByRef StringArray() As String) As String()
'This function removes trailing empty elements from arrays
'Searching from the last element backwards until a non-blank is found
Dim i As Long
For i = UBound(StringArray) To LBound(StringArray) Step -1
If StringArray(i) <> "" Then Exit For
Next i
If i < LBound(StringArray) Then i = LBound(StringArray)
'Creating an array with the correct size to hold the non-blank elements
Dim OutArr() As String
OutArr = StringArray
ReDim Preserve OutArr(LBound(StringArray) To i)
TrimArray = OutArr
End Function
You would use it like so:
Dim Output() As String
Output = TrimArray(initials)
MsgBox Join(Output, ".") & "."
You could build it like this instead of using Join():
ActiveCell.Offset(0, 2).Value = initials(0)
For Counter = 1 To 15
If initials(Counter) <> "" Then
ActiveCell.Offset(0, 2).Value = ActiveCell.Offset(0, 2).Value + "." + initials(Counter)
End If
Next Counter

how can i fill a treeview from a database in vb.net?

i'm currently building an application that requires me to dynamically fill a tree view
i wrote the following code but the filling always stop at level 1
Private Sub TreeDraw(ByVal TreeRoot As String)
'Throw New NotImplementedException
TVNew.Nodes.Clear()
Dim con = New OleDbConnection(StrConn)
Dim strSql = "Select * from Tree WHERE TreeName = '" & _
TreeRoot.Trim & "' AND levelNum = 0" & _
" ORDER BY nodeID ASC"
Dim da = New OleDbDataAdapter(strSql, con)
Dim ds As New DataSet
Dim lvl = 0
Try
da.Fill(ds, "Tree")
Do While ds.Tables(0).Rows.Count > 0
If lvl = 0 Then
TVNew.Nodes.Add(ds.Tables(0).Rows(0)(4))
Else
For Each row As DataRow In ds.Tables(0).Rows
For Each node As TreeNode In TVNew.Nodes
If node.Text = row(3) Then
TVNew.SelectedNode = node
TVNew.SelectedNode.Nodes.Add(row(4))
End If
Next
Next
End If
'MsgBox(lvl.ToString)
lvl = lvl + 1
da.Dispose()
ds.Tables.Clear()
strSql = "Select * from Tree WHERE TreeName = '" & _
TreeRoot.Trim & "' AND levelNum =" & lvl & _
" ORDER BY nodeID ASC"
da = New OleDbDataAdapter(strSql, con)
da.Fill(ds, "Tree")
Loop
Catch ex As Exception
MsgBox(ex.Message & Chr(13) & da.SelectCommand.CommandText _
, vbOKOnly, Application.ProductName)
Exit Sub
End Try
TVNew.ExpandAll()
End Sub
can any one help please?

How to get pre-selected combo box value from combo box?

Here as you can see I'm not using combox_click because it is declared above and the current one is another function to be called without clicking, here my question is how do I get the pre-selected value from the combo box without clicking on the box?
Public Sub ComDep_Change()
Dim sQuery As String
Dim oRS As New ADODB.Recordset
Dim rsPR As New ADODB.Recordset
Dim dateFormat As String
Dim sPONO As String
Dim sPOAmt As String
'oRS.Open "po_receiveable", PRCnn, adOpenDynamic, adLockOptimistic
combVal = ComDep.List(ComDep.ListIndex)
If Not combVal = "ALL_DEPT" And frmMain.OptLatestCN.Value = True Then
'MsgBox ("Works")
dateFormat = "#" + CStr(Day(Now)) + "/" + CStr(Month(Now)) + "/" + CStr(Year(Now) - 3) + "#"
sQuery = "select * from CN_Request_Header where dept = '" & combVal & "' and requestdate >= " & dateFormat & ""
' sQuery = "Select PO_No, PO_Requestor, PO_Req_Dept, PO_Status, PO_Approval_M, PO_Approval_GM, PO_Approval_D, PO_HRApproval, VC_No, TH_Sup_Inv, PO_HR_Rmk, PO_Req_Date, PO_SupplierName, PO_OverallAmt from PR_INFO where PO_Req_Dept = '" & combVal & "'"
' MsgBox ("Result" & sQuery)
rsPR.Open sQuery, PRCnn, adOpenDynamic, adLockOptimistic
lvwCreditNote.ListItems.Clear
Do While Not rsPR.EOF
Set listitem = frmMain.lvwCreditNote.ListItems.Add
With listitem
.Text = CStr(Trim(rsPR!requestID))
.SubItems(1) = Trim(rsPR!requestID)
.SubItems(2) = Format(CStr(rsPR!requestdate), "dd-mmm-yy")
.SubItems(3) = Trim(rsPR!createby)
.SubItems(4) = Trim(rsPR!dept)
.SubItems(5) = Trim(rsPR!reqstatus)
If IsNull(rsPR!custName) Then
.SubItems(6) = ""
Else
.SubItems(6) = Trim(rsPR!custName)
End If
If IsNull(rsPR!cnamt) Then
.SubItems(7) = "0.00"
Else
.SubItems(7) = Format(rsPR!cnamt, "#,###,##0.00")
End If
You would get the currently SELECTED element in a combobox
by using the SELECTEDINDEX Property
If nothing is selected then you get the value -1 returned to you.
If something is selected it will be in the range 0 to Combox.Count - 1
To get the text for the selected item
You could use something like...
Dim SelIndex as Integer
Dim SelText As String
'
SelIndex = MyCombobox.SelectedIndex
If (SelIndex >= 0) AND (SelIndex <= MyCombobox.Count - 1) Then
SelText = MyCombobox.List(Index)
Else
'Nothing was selected in the combobox
End If

How to refresh a Loop or update a Loop in VBA

So I have this list that is X rows long.
Each has 5 columns: Equipment, Type, Material, Size and Price this is in the Sheet2.
I also have a database in sheet1 with the same column filled in. I have written a code in VBA that for each row in Sheet2 I can fill in Equipment, Type, Material and Size and it will search in the database in sheet1 the matching price for those criteria and past this under the column Price in Sheet2.
Now the problem that I have is if I for example filled in row 1, row 2 and row 3 after each other it works and gives me the price but if I later want to change the variables in row 1 or 2 it doesn't change/update the Price but it still works for row 3 and forward.
How do I make it so that it does change/Update the price in row 1 and 2 if I change the variables there.
my code:
Option Explicit
Public r As Long
Public Const adOpenStatic = 3
Public Const adOpenKeySet = 1
Public Const adLockReadOnly = 1
Sub cmdSearch_Click()
Dim strCriteriaEquipment As String
Dim strCriteriaType As String
Dim strCriteriaMaterial As String
Dim strCriteriaSize As String
Dim strSQL As String
Dim strSourceTable As String
Dim c As Long, LR As Long
LR = Cells(Rows.Count, 2).End(xlUp).Row
For r = 1 To LR
c = 2
With Worksheets("Summary")
strCriteriaEquipment = Worksheets("Summary").Cells(r, c).Value
strCriteriaType = Worksheets("Summary").Cells(r, c + 1).Value
strCriteriaMaterial = Worksheets("Summary").Cells(r, c + 2).Value
strCriteriaSize = Worksheets("Summary").Cells(r, c + 3).Value
End With
Next r
strSourceTable = "[DB$" & Replace(Worksheets("DB").Range("SourceData").Address, "$", "") & "]"
strSQL = "SELECT [Price] FROM " & strSourceTable & vbNewLine
strSQL = strSQL & "WHERE [Equipment]= """ & strCriteriaEquipment & """" & vbNewLine
strSQL = strSQL & "AND [Type]=""" & strCriteriaType & """" & vbNewLine
strSQL = strSQL & "AND [Material]=""" & strCriteriaMaterial & """" & vbNewLine
strSQL = strSQL & "AND [Size]=""" & strCriteriaSize & """;"
Dim rstRecordSet As Object 'ADODB.Recordset
Dim con As Object 'ADODB.Connection
Dim strWorkBookPath As String
strWorkBookPath = ThisWorkbook.FullName
Set con = CreateObject("ADODB.Connection")
Set rstRecordSet = CreateObject("ADODB.RecordSet")
con.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strWorkBookPath & ";" & _
"Extended Properties=""Excel 8.0;HDR=Yes"";"
rstRecordSet.Open strSQL, con, adOpenStatic, adLockReadOnly
With Worksheets("Summary")
For r = r - 29 To LR
c = 5
If Not (rstRecordSet.EOF And rstRecordSet.BOF) Then
.Range("ResultTable").Cells(r, c).CopyFromRecordset rstRecordSet
Else
.Range("ResultTable").Cells(r, c).Value = "Data Not Found!"
End If
Next r
End With
rstRecordSet.Close
con.Close
Set rstRecordSet = Nothing
Set con = Nothing
strWorkBookPath = vbNullString
strSQL = vbNullString
strCriteriaEquipment = vbNullString
strCriteriaType = vbNullString
strCriteriaMaterial = vbNullString
strCriteriaSize = vbNullString
strSourceTable = vbNullString
End Sub
Public Function UniqueStringWithDelimiter(varArray As Variant, strDelimiter As String) As Variant
Dim varTemp() As Variant
Dim lngLoop As Long
Dim strConcat As String
ReDim Preserve varTemp(0 To 0)
varTemp(0) = varArray(0, 0)
strConcat = strConcat & varArray(0, 0)
For lngLoop = 1 To UBound(varArray, 2)
If InStr(1, strConcat, varArray(0, lngLoop), vbTextCompare) = 0 Then
strConcat = strConcat & strDelimiter & varArray(0, lngLoop)
End If
Next lngLoop
UniqueStringWithDelimiter = strConcat.
strConcat = vbNullString
Erase varTemp
End Function
Now to update everytime I change something in Sheet2 I just wrote this:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Call cmdSearch_Click
End Sub
So again my question how do I update/change the price if I change a variable in row 1 or row 2 if row 3 was the last row that was used in the sheet.
This is the datbase that I am using:
This is Sheet2:
1) One immediate problem I see that will cause your issue (and there may be more, but I don't have time to dissect so much at this moment), is that the initial loop:
For r = 1 To LR
c = 2
With Worksheets("Summary")
strCriteriaEquipment = Worksheets("Summary").Cells(r, c).Value
strCriteriaType = Worksheets("Summary").Cells(r, c + 1).Value
strCriteriaMaterial = Worksheets("Summary").Cells(r, c + 2).Value
strCriteriaSize = Worksheets("Summary").Cells(r, c + 3).Value
End With
Next r
is not doing what you may expect. At the end of this loop you only have set the values for the last row of data (I suspect row 3) to pass into your query.
You'll need to write your queries inside this loop as well so that the query is run for each set of criteria in each line.
For example:
For r = 1 to LR
c = 2
With Worksheets("Summary")
'code to set criteria
End With
'code to download data price
'code to stick data and price in summary tab
Next r
2) Also, make sure to qualify all your objects. The line
LR = Cells(Rows.Count, 2).End(xlUp).Row
may return different results if the sheet you desire to be active is not actually active. Better to say this, for example, and leave out guess works:
LR = Worksheets("Summary").Cells(Rows.Count, 2).End(xlUp).Row
3) Using Worksheet_SelectionChange will fire your code every time you move from one to another in your worksheet. If you want to only fire the code when you make a change to the criteria in your data, use Worksheet_Change instead. You can also define which specific cells being changes will run the code as well.

Resources