Using arrays for updates in visual basic - arrays

this is my existing code:
DBConn.BeginTrans
strSQL = "DELETE tblAvailable WHERE "
strSQL = strSQL + "(intResortID = " + Session("TypeID") + ")"
strSQL = strSQL + " AND (dtm BETWEEN CONVERT(DATETIME,'" + cstr(Year(dtmStart)) + "-" + cstr(Month(dtmStart)) + "-" + cstr(Day(dtmStart)) + "', 102)"
strSQL = strSQL + " AND CONVERT(DATETIME,'" + cstr(Year(dtmEnd)) + "-" + cstr(Month(dtmEnd)) + "-" + cstr(Day(dtmEnd)) + "', 102))"
'SY SINGH
'Add code to only delete out room types contained in the spreadsheet
Dim i
strSQL = strSQL & "AND (strRoomType='" & strRooms(0) & "'"
For i = 1 to m_Rooms
strSQL = strSQL & " OR strRoomType='" & strRooms(i) & "'"
next
strSQL = strSQL & ")"
I want to change it to do an update instead, setting curprice where strRoomType is equal to the array of rooms.
this is what I have come up with so far
strSQL = "Update tblAvailable set curprice ="+ FixNumber(curprice (intCurrentData))
response.Write(strSQL)
strSQL = strSQL +"WHERE intResortID = " + Session("TypeID")
response.Write(strSQL)
strSQL = strSQL + " AND dtm BETWEEN CONVERT(DATETIME,'" + cstr(Year(dtmStart)) + "-" + cstr(Month(dtmStart)) + "-" + cstr(Day(dtmStart)) + "', 102)"
response.Write(strSQL)
strSQL = strSQL + " AND CONVERT(DATETIME,'" + cstr(Year(dtmEnd)) + "-" + cstr(Month(dtmEnd)) + "-" + cstr(Day(dtmEnd)) + "', 102)"
response.Write(strSQL)
dim i
strSQL = strSQL + " AND (strRoomType='" & strRooms(0) & "'"
response.Write(strSQL)
For i = 1 to m_Rooms
strSQL = strSQL & " OR strRoomType='" & strRooms(i) & "'"
response.Write(strSQL)
next
strSQL = strSQL & ")"
response.Write(strSQL)
DBConn.Execute strSQL
this is the error I am receiving:
dtm'dtm' OR strRoomType='obeqvb'dtm' OR strRoomType='obeqvb')
Microsoft OLE DB Provider for SQL Server error '80040e14'
Incorrect syntax near 'obeqvb'.
/upload_excel_v3.asp, line 230
obeqvb is my strroomtype and dtm is my date

You should escape any single-quotes in your values by doubling them up
'my'roomtype should be 'my''roomtype'
And you're better off using where strRoomType in(...) instead of "or"

Related

VB.NET call a button function

How do i go about this code, I want to call amountpayable on the confirm purchase button but it says amount payable is not declared and I am having a hard time trying to pass the value from another function... Anyone knows a quick easy fix? I am not familiar with visual basic so if someone can share a light on this query I just want an easy one, one i can easily understand
Here is the code
Private Sub BtnAddOrder_Click(sender As Object, e As EventArgs) Handles BtnAddOrder.Click
Dim AddOns As String
Dim BlackPearl As String
Dim Oreo As String
Dim Nata As String
Dim CoffeeJelly As String
Dim CreamCheese As String
AddOns = " "
BlackPearl = " "
Oreo = " "
Nata = " "
CoffeeJelly = " "
CreamCheese = " "
If ChkBoxBlackPearl.Checked = True Then
AddOns = "Black Pearl"
End If
If ChkBoxOreo.Checked = True Then
AddOns = AddOns & "," & " Oreo"
End If
If ChkBoxNata.Checked = True Then
AddOns = AddOns & "," & " Nata De Coco"
End If
If ChkBoxCoffeeJelly.Checked = True Then
AddOns = AddOns & "," & " Coffee Jelly"
End If
If ChkboxCreamCheese.Checked = True Then
AddOns = AddOns & "," & " CreamCheese"
End If
Dim Payment As String
Payment = " "
If RbtnGcash.Checked = True Then
Payment = "Gcash"
End If
If RbtnDebit.Checked = True Then
Payment = "Debit Card"
End If
If RbtnCoins.Checked = True Then
Payment = "Coins.ph"
End If
If RbtnCash.Checked = True Then
Payment = "Cash"
End If
Dim DiscountRate As Double
If RbtnPWD.Checked = True Then
DiscountRate = 0.05
End If
If RbtnSenior.Checked = True Then
DiscountRate = 0.1
End If
If RbtnStudent.Checked = True Then
DiscountRate = 0.03
End If
If RbtnDiscountNone.Checked = True Then
DiscountRate = 0
End If
Dim Transaction As String
Transaction = " "
If RbtnDelivery.Checked = True Then
Transaction = "15"
End If
If RbtnWalkin.Checked = True Then
Transaction = "None"
End If
TxtTotalAddOn.Text = Val(TxtBlackPearl.Text) + Val(TxtOreo.Text) + Val(TxtNataDeCoco.Text) + Val(TxtCoffeeJelly.Text) + Val(TxtCreamCheese.Text)
Dim Total As Integer
Dim DiscountPrice As Double
Dim AmountPayable As Double
Total = Val(TxtTotalAddOn.Text) + Val(TxtSizeprice.Text) + Val(TxtDeliveryFee.Text)
DiscountPrice = Total * DiscountRate
AmountPayable = (Total - DiscountPrice) * Val(ComboQuantity.Text)
If AddOns.Length <> 0 Then
MessageBox.Show("********************************" + vbCr + "Troo Tea Ordering System" + vbCr + "********************************" + vbCr + "Choosen DRINK: " + ComboDrink.Text + vbCr + "********************************" + vbCr + "Quantity: " + ComboQuantity.Text + vbCr + "********************************" + vbCr + "Size: " + Sizename + vbCr + "********************************" + vbCr + "Price " + TxtSizeprice.Text + vbCr + "********************************" + vbCr + "AddOns: " + AddOns + vbCr + "********************************" + vbCr + "Total AddOns " + TxtTotalAddOn.Text + vbCr + "********************************" + vbCr + "Delivery Fee" + TxtDeliveryFee.Text + vbCr + "********************************" + vbCr + "Discount " + TxtDiscount.Text + vbCr + "Total " + Total.ToString + vbCr + "Amount Payable: " + AmountPayable.ToString + vbCr + "********************************" + vbCr + "*******************" + vbCrLf + "Thank You For Your Order" + vbCrLf + "*******************")
End If
TxtOrderDetails.Text = ("Customer Name: " + TxtCustomername.Text + vbCrLf + "Phone Number: " + TxtPhone.Text + vbCrLf + "Address: " + TxtAddress.Text + vbCrLf + "***********************************************************" + vbCrLf + "Choosen DRINK: " + ComboDrink.Text + vbCrLf + "Quantity: " + ComboQuantity.Text + vbCrLf + "Size: " + Sizename + vbCrLf + "Price: " + TxtSizeprice.Text + vbCrLf + "AddOns: " + AddOns + vbCrLf + "Total AddOns: " + TxtTotalAddOn.Text + vbCrLf + "Delivery Fee: " + TxtDeliveryFee.Text + vbCrLf + "Mode Of Payment: " + Payment + vbCrLf + "Discount Rate for Each Order: " + TxtDiscount.Text + vbCrLf + "Total Price Per Order: " + Total.ToString + vbCrLf + "Amount Payable: " + AmountPayable.ToString + vbCrLf + "***********************************************************" + vbCrLf + "Thank You For Your Order" + vbCrLf + "***********************************************************" + vbCrLf + "Date Of Transaction: " + DateTimePicker1.Text)
End Sub
Private Sub BtnConfirm_Click(sender As Object, e As EventArgs) Handles BtnConfirm.Click
End Sub
End Class
Since you can't modify the signature of an event handler, you won't be able to pass the variable from one handler to the other. Instead, declare the variable as a field within the class.
See additional comments added in the code below. I simply cut out some of the code you provided for brevity and shifted the declaration of the AmountPayable to outside of the sub it was originally declared in.
You can read more on variable scope here
Private AmountPayable As Double 'move this declaration outside of the sub
Private Sub BtnAddOrder_Click(sender As Object, e As EventArgs) Handles BtnAddOrder.Click
Dim Total As Integer
Dim DiscountPrice As Double
Total = Val(TxtTotalAddOn.Text) + Val(TxtSizeprice.Text) + Val(TxtDeliveryFee.Text)
DiscountPrice = Total * DiscountRate
'variable can be assigned here
AmountPayable = (Total - DiscountPrice) * Val(ComboQuantity.Text)
End Sub
Private Sub BtnConfirm_Click(sender As Object, e As EventArgs) Handles BtnConfirm.Click
MessageBox.Show("Your Total is $" & AmountPayable) 'variable can be accessed here
End Sub
End Class

How do I insert value into dataset at runtime using microsoft SQL server in vb.net

this is the code I am using for trying to insert a row to my dataset.
It executes properly till sqlConnection is opened. But the nonQuery execution throws a 'System.Data.SqlClient.SqlException' I believe there is something wrong with my connection string, I copied it from the app./config file and I cannot figure out what is wrong. Also, I know I should use a parameterized SQL query, I will implement that later.
Dim sqlConnection1 As New System.Data.SqlClient.SqlConnection("Data Source=(localdb)\MSSQLLocalD;Initial Catalog=ContactInfo;Integrated Security=True;Pooling=False")
Dim cmd As New SqlClient.SqlCommand
cmd.CommandType = CommandType.Text
cmd.CommandText = "INSERT INTO Table (ID, FirstName, MiddleName, LastName, Type, Telephone, Extension, Email) VALUES (" + row.ID.ToString + "," + "'" + row.FirstName + "'" + "," + "'" + row.MiddleName + "'" + "," + "'" + row.LastName + "'" + "," + "'" + row.Type + "'" + "," + row.Telephone.ToString + "," + "'" + row.Extension + "'" + "," + "'" + row.Email + "')"
cmd.Connection = sqlConnection1
sqlConnection1.Open()
cmd.ExecuteNonQuery()
sqlConnection1.Close()
First, Don't think that you can name your table "Table" so change it to your real table name and it should run
And USE SQL PARAMETERS!
Second, get the result of ExecuteNonQuery to a variable so you can check, if a record was written or not.

Automation Error when executing SQL Server Script in Excel VBA

I am opening an SQL Server Connection in EXCEL VBA and on the objMyCmd.Execute line when it is using the SQL script I am getting this error message:
"Run-time error '-2147217900 (80040e14)') Automation error"
I have reviewed other SO posts that seem to reference an issue with the connection string itself, but I don't believe that is the issue as I am able to pull the first few variables listed when eliminating the rest of the SQL script.
I have attempted to review the SQL code to see if I am using an incorrect format, or if the language is not written properly and I am not able to determine the issue. I am hoping with some Q & A we may notice something I have missed in how this is written? Please let me know if there is additional information I can provide, below is the code up to the point of error.
Sub SQL_GetAgentChart()
Dim dtDate As Date
Dim myTable As ListObject
Dim DataServer As String
Dim Database As String
Dim constring As String
DataServer = "GLSSQLMADP2"
Database = "PERF_MGMT_BWRSRV_PROD"
constring = "Driver={SQL Server};Server=" & DataServer & "; Database=" & Database & "; Trusted_Connection=yes"
Dim AVStartDate As Date
Dim AVEndDate As Date
Dim RepID As Long
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Set myTable = Worksheets("Witness").ListObjects("tblWitness")
AVStartDate = DateValue("Mar 01, 2016")
AVEndDate = DateValue("Mar 31, 2016")
RepID = 2040
'Open Connection'
objMyConn.ConnectionString = constring
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = " " & _
"SELECT PERSN_XTRNL_ID_NR, SOURCE, LOGGINGTS, DD7, CUREREASON, CUREDATE, LNSTATUS " & _
"FROM TTB " & _
"WITH INCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN PERSONNEL P ON T.PERSONNELID = P.PERSONNELID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE T.PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 1 " & _
"AND DD7 > 0), OUTCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN AVAYA A ON T.UID = A.TTBUID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 0 " & _
"AND A.AVAYAGROUP IN ('15', '1A', '1B', '1C', '1D', '1E', '1F', '1G', '1H') " & _
"AND DD7 > 0) "
objMyCmd.CommandType = adCmdText
objMyCmd.Execute

run time error 1004 general odbc error refresh backgroundquery false

I have a working VBA code which runs as:
wsEnd.Select
Range("A:AQ").Delete
strSQL = "Select *
strSQL = strSQL & " FROM [XXX].[ABCCustomer] As A"
strSQL = strSQL & " Left join"
strSQL = strSQL & " (Select * "
strSQL = strSQL & " From [XXX]..[ABCCustomer]"
strSQL = strSQL & " where LineageId = '123' ) B"
strSQL = strSQL & " on a.product = b.product and a.[StartDate] = b.[StartDate]"
strSQL = strSQL & " where (a.EndDate <> b.EndDate)"
strSQL = strSQL & " and a.NewEndDate is NULL AND B.NewEndDate IS NULL"
strSQL = strSQL & " and a.Id = '456"
strSQL = strSQL & " order by b.ProductType"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
"ODBC;DRIVER=SQL Server;SERVER=XXX\SQL01;UID=;Trusted_Connection=Yes;APP=2007 Microsoft Office system;WSID=XXX;DATA" _
), Array("BASE=master")), Destination:=Range("$A$1")).QueryTable
.CommandText = strSQL
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_XXX_C"
.Refresh BackgroundQuery:=False
End with
I have two other scripts starting after the End With but inside the same sub all using the same VBA just different SQL, which all work perfectly fine.
Then I have this very annoying forth, which is causing my a real headache, that goes as follows:
strSQL = "Select *
strSQL = strSQL & " FROM [XXX].[ABCCustomer] As A"
strSQL = strSQL & " Left join"
strSQL = strSQL & " (Select * "
strSQL = strSQL & " From [XXX]..[ABCCustomer]"
strSQL = strSQL & " where Id = '123' ) B"
strSQL = strSQL & " on a.product = b.product and a.[StartDate] = b.[StartDate]"
strSQL = strSQL & " where (a.EndDate = b.EndDate)"
strSQL = strSQL & " and a.NewEndDate is Not NULL AND B.NewEndDate not NULL"
strSQL = strSQL & " and a.Id = '456"
strSQL = strSQL & " order by b.Product"
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array(Array( _
"ODBC;DRIVER=SQL Server;SERVER=XXX\SQL01;UID=;Trusted_Connection=Yes;APP=2007 Microsoft Office system;WSID=XXX;DATA" _
), Array("BASE=master")), Destination:=Range("$A$1")).QueryTable
.CommandText = strSQL
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_XXX_D"
.Refresh BackgroundQuery:=False
End With
End Sub
When running the code, the first three come back fine but the forth says
run time error 1004 general odbc error
and stops the code at backgroundquery=false.
I have lifted the SQL code into SQL and it works perfectly fine there and have even tried running it on a separate excel document and that doesn't give any joy.
The VBA is copy and pasted and only the list object table name is changed i.e. from C to D
I have tried to change backgroundquery:=false to background:=refresh, this works but I get a message saying
run time error 1004 This operation cannot be done because the data is refreshing in the background.
The error went away after a computer reset. Really sorry, but thanks for all those who responded.
Thanks
Matt
This isn't an answer to the question. But it is relevant, since the reason for writing it like this was to make it easier to read.
Original Code: This does a nice job of lining up the characters to read the statement, but is redundant by defining the value of strSQL for every line item.
strSQL = "Select *
strSQL = strSQL & " FROM [XXX].[ABCCustomer] As A"
strSQL = strSQL & " Left join"
strSQL = strSQL & " (Select * "
strSQL = strSQL & " From [XXX]..[ABCCustomer]"
strSQL = strSQL & " where LineageId = '123' ) B"
strSQL = strSQL & " on a.product = b.product and a.[StartDate] = b.[StartDate]"
strSQL = strSQL & " where (a.EndDate <> b.EndDate)"
strSQL = strSQL & " and a.NewEndDate is NULL AND B.NewEndDate IS NULL"
strSQL = strSQL & " and a.Id = '456"
strSQL = strSQL & " order by b.ProductType"
Modified: Aside from the color formatting getting lost in translation. This tells anyone reading it that the variable is getting set once and eliminates redundant characters to have to scan over.
strSQL = "Select * " & _
"FROM [XXX].[ABCCustomer] As A " & _
"Left join " & _
"(Select * " & _
"From [XXX]..[ABCCustomer] " & _
"where LineageId = '123' ) B " & _
"on a.product = b.product and a.[StartDate] = b.[StartDate] " & _
"where (a.EndDate <> b.EndDate) " & _
"and a.NewEndDate is NULL AND B.NewEndDate IS NULL " & _
"and a.Id = '456 " & _
"order by b.ProductType"

VBA Contains Function

I'm currently making an Excel function that connects to an SQL server and retrieves data as long as it matches the given criteria.
Public Function VehModelUnitsCount(VehModel As String, fran As String, Site As Integer, SaleType As String, StartDate, EndDate, New As Integer) As Variant
Application.Volatile
If adoCN Is Nothing Then Call SetUpConnection
Set adoRS = New ADODB.Recordset
EvoStartDate = Format(StartDate, "yyyy/mm/dd")
EvoEndDate = Format(EndDate, "yyyy/mm/dd")
strSQL = "SELECT COUNT(*) As RCOUNT FROM CARTYPES RIGHT OUTER JOIN CARS ON CARTYPES.Description = CARS.Type LEFT OUTER JOIN CARS2 ON CARS.[Stock Number] = CARS2.[Stock Number]" & Chr(13)
strSQL = strSQL & "WHERE (CARTYPES.NewSale = " & New & " )" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.Franchise = '" & fran & "')" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.Site = " & Site & ")" & Chr(13)
strSQL = strSQL & "AND (CARTYPES.SaleTypeDesc = '" & SaleType & "')" & Chr(13)
strSQL = strSQL & "AND (CARS2.InvoiceDate BETWEEN '" & StartDate & "' AND '" & EndDate & "')" & Chr(13)
strSQL = strSQL & "AND (CARS.Invoiced = '1')" & Chr(13)
Rem strSQL = strSQL & "AND (CARS.Model = '" & VehModel & "')" & Chr(13)
[THIS ONE] - strSQL = strSQL & "AND (CARS.Model CONTAINS '" & VehModel & "')" & Chr(13)
adoRS.Open strSQL, adoCN, adOpenForwardOnly, adLockReadOnly
VehModelUnitsCount = adoRS.Fields("RCOUNT").Value
adoRS.Close
End Function
The string marked with [THIS ONE] is the one I am struggling with, I need to find out whether or not the cell contains the given string, but apparently using 'CONTAINS' doesn't work.
Any help on completing this would be amazing.
Thank you.
You could try -
strSQL = strSQL & "AND (CARS.Model LIKE '%" & VehModel & "%')" & Chr(13)

Resources