I'm new to vb.net and I'm creating thesis project in our school. I want to fetch data from my excel file where cells was merge and it keeps on popping conversion from type 'Range' to type 'String' is not valid. Here's my code that I copied and credits for them:
Try
con.Open()
workbook = app.Workbooks.Open(fileOpener.SelectedPath + "\ahrmt.xlsx")
worksheet = workbook.Worksheets("Sheet1")
curbook = 0
Me.Text = String.Format("{0:F0}%", ((curbook / books) * 100)) + " of records has been imported."
Dim cmd As New MySqlCommand
Dim maxrow As Integer = 9
Dim noRecs, AYear As Integer
Dim semester, course As String
Me.lblWait.Visible = True
'=====================================
Dim str As String
str = worksheet.Range("A6").Text
If str.Contains("FIRST SEMESTER") = True Then
semester = "First Semester"
Else
semester = "Second Semester"
End If
Dim exAY = Regex.Replace(worksheet.Cells(6, 1), "\D", "")
AYear = exAY
Dim AcadY As New System.Text.StringBuilder()
For i As Integer = 0 To exAY.Length - 1
AcadY.Append(exAY(i))
If i Mod 4 = 3 AndAlso i > 0 AndAlso i < exAY.Length - 1 Then
AcadY.Append(" - ")
End If
Next
course = "Associate in Hotel and Restaurant Management Technology"
'=======================================
'--------to get the total rows
For x As Integer = 9 To worksheet.Rows.Count
If worksheet.Cells(x, 2).Value = Nothing Then
Exit For
Else
maxrow += 1
End If
Next
'----------for inserting records
For i As Integer = 9 To worksheet.Rows.Count
If worksheet.Cells(i, 2).Value = Nothing Then
Exit For
Else
Me.ProgressBar1.Visible = True
Me.ProgressBar1.Value += 1
Me.ProgressBar1.Maximum = maxrow - 9
Me.lblImport.Text = String.Format("{0:F0}%", ((ProgressBar1.Value / ProgressBar1.Maximum) * 100))
cmd.Connection = con
cmd.CommandText = "INSERT INTO tblsif(IDNo, Status, FName, MName, LName, Gender, YearLevel, Semester, AcadYear, PresCourse) " & _
"VALUES('" & worksheet.Cells(i, 2).Value & "','" & enrolledStat & "','" & worksheet.Cells(i, 5).Value & "','" & worksheet.Cells(i, 6).Value & "'," & _
"'" & worksheet.Cells(i, 4).Value & "','" & worksheet.Cells(i, 10).Value & "','" & worksheet.Cells(i, 1).Value & "','" & semester & "','" & AcadY & "','" & course.ToString & "')"
cmd.ExecuteNonQuery()
noRecs += 1
Me.lblTotalRec.Text = "Importing " + noRecs.ToString + " records from AHRMT Course."
End If
Next
'workbook.Save()
workbook.Close()
app.Quit()
Catch ex As Exception
MsgBox(ex.Message)
End Try
Me.ProgressBar1.Value = 0
Me.ProgressBar1.Visible = False
Me.lblTotalRec.Text = Nothing
Me.lblImport.Text = Nothing
con.Dispose()
con.Close()
curbook = 1
Me.Text = String.Format("{0:F0}%", ((curbook / books) * 100)) + " of records has been imported."
Hope you can help me.
Related
Aim is to reset Month Value and Year value every month and every year, however, it is not resetting. Please help.
Private Sub Proforma_Number_Generator_Command_Click()
Dim vLastM As Variant
Dim accM As Integer
Dim vLastY As Variant
Dim accY As Integer
'Sets the date of the Proforma Invoice Number to Today'
'Me.Proforma_Invoice_Date = Format(Date, "yyyy-mm-dd")
vLastM = DMax("[Month Value]", "[Proforma Invoice Form Table]", _
"PI_Month='" & Me.PI_Month.Value & "' AND PI_Year ='" & _
Me.PI_Year.Value & "'")
If IsNull(vLastM) Then
accM = 1
Else
accM = vLastM + 1
End If
Me.Month_Value = accM
'Year'
vLastY = DMax("[Year Value]", "[Proforma Invoice Form Table]", _
"PI_Year='" & Me.PI_Year.Value & "'")
If IsNull(vLastY) Then
accY = 1
Else
accY = vLastY + 1
End If
Me.Year_Value = accY
Me.Order_No = Format("ON" & "-" & Format(Date, "yyyy") & "-" & Me.Year_Value)
End Sub
It is confusing what your goal is, as month isn't used, but try this reduced code:
Private Sub Proforma_Number_Generator_Command_Click()
' Month. Not used?
Me!Month_Value.Value = Nz(DMax("[Month Value]", "[Proforma Invoice Form Table]", _
"PI_Month=" & Me!PI_Month.Value & " AND PI_Year ='" & _
Me.PI_Year.Value & ""), 0) + 1
' Year.
Me!Year_Value.Value = Nz(DMax("[Year Value]", "[Proforma Invoice Form Table]", _
"PI_Year=" & Me!PI_Year.Value & ""), 0) + 1
Me!Order_No.Value = Format("ON" & "-" & Format(Date, "yyyy") & "-" & Me!Year_Value.Value & "-" & )
End Sub
I'm not a VBA expert. I simply copy from the net and try to utilize in my program. however, below is my codes. I'm trying to calculate a finish date considering offdays, but the issue is sometime the time required is less than one day in that case it is calculating as 1 day. How can I calculate it by hours. Suppose if the startdate is 1-jan-2019 6:00 am and the required time to produce is 6 hours than the finish time should be 1-jan-2019 12:00pm
Public Function AddFinishDate(StartDate As Date, ReqDays As Double, FriOff As Boolean) As Date
Dim rst As Recordset
Dim db As Database
Dim FinishDate As Date
Dim icount As Integer
On Error GoTo errhandlers:
Set db = CurrentDb
Set rst = db.OpenRecordset("tblHoliday", dbOpenSnapshot)
icount = 0
FinishDate = StartDate
Do While icount < ReqDays
FinishDate = FinishDate + 1
If Weekday(FinishDate, vbSaturday) <> 7 Or FriOff = False Then
rst.FindFirst "(HolidayDate)= #" & FinishDate & "#"
If rst.NoMatch Then
icount = icount + 1
End If
End If
Loop
AddFinishDate = FinishDate
exit_errhandlers:
rst.Close
Set rst = Nothing
Set db = Nothing
AddFinishDate = FinishDate
Exit Function
errhandlers:
MsgBox Err.Description, vbExclamation
Resume Next
End Function
Private Sub Command53_Click()
Dim dbs As DAO.Database
Set dbs = CurrentDb()
dbs.Execute "UPDATE BalFitToFabricate " & "SET used = false , startdate ="""",finishdate ="""";"
Me.Refresh
End Sub
Private Sub Command71_Click()
Dim dbs As DAO.Database, Initrst, rst, rst2 As DAO.Recordset
Dim strSQL
Dim ClientsTableQuery, SalesRepList As TableDef
Dim DataB As Database
Dim ClientQD As QueryDef
Dim rstClient As DAO.Recordset
Dim DurationTotal, Counter, i As Integer
Dim LowDate1, LowDate2 As Date
Dim tmpArray(10), FieldArray(10), TempDate1, TempDate2 As Date
Dim TotalDailyHrs, TempDailyHours As Integer
Dim FirstTimeIn As Boolean
FirstTimeIn = False
TotalDailyHrs = Forms("BalFitToFabricate").Text49.Value
TempDailyHours = TotalDailyHrs
Set dbs = CurrentDb()
ClientsTableQuery = "BalFitToFabricate"
'strSQL = "Select * from Client_Table"
Set DataB = CurrentDb()
Set rstClient = DataB.OpenRecordset(ClientsTableQuery)
rstClient.MoveFirst
Counter = 0
Set Initrst = dbs.OpenRecordset("SELECT * FROM BalFitToFabricate;")
'Set rst = dbs.OpenRecordset("SELECT * FROM BalFitToFabricate;")
Set rst = dbs.OpenRecordset("SELECT * FROM (SELECT * FROM (SELECT * FROM BalFitToFabricate WHERE Used = false)) WHERE FinishDate = (select min(FinishDate) from BalFitToFabricate where Used = false);")
Set rst2 = dbs.OpenRecordset("SELECT * FROM BalFitToFabricate WHERE isnull(StartDate) order by NULLSORTER,Req_Del_Date,Priority;")
'Autonumrst.Requery
'MsgBox Initrst.RecordCount & " " & rst.RecordCount & " " & rst2.RecordCount
'First Loop
Do Until rstClient.EOF = True
If TempDailyHours <= TotalDailyHrs Then
'Autonumrst.Requery
'If FirstTimeIn = False Then
' TotalDailyHrs = TotalDailyHrs - TempDailyHours
'End If
TempDailyHours = Initrst![CreqHours]
Dim Autonumrst, Valuesrst As DAO.Recordset
Dim strSQL2, strSQL3 As String
'strSQL2 = "SELECT [Crew Hours] FROM Table2 where AutoNum = " & Initrst!Autonum & "and used = false;"
strSQL2 = "SELECT [CreqHours] FROM Table2 where Used = False;"
strSQL3 = "SELECT * FROM Table2 where Used = False;"
Set Autonumrst = CurrentDb.OpenRecordset(strSQL2)
Set Valuesrst = CurrentDb.OpenRecordset(strSQL3)
' new code:
'Stopped 2 lines
'TempDailyHours = Autonumrst![Crew Hours]
'Autonumrst.Requery
'Autonumrst.Close
'TempDailyHours = dbs.Execute "select BalFitToFabricate " & "SET startdate = #" & TempDate1 & "# WHERE Autonum = " & Initrst!Autonum & ";"
TotalDailyHrs = TotalDailyHrs - TempDailyHours
If TotalDailyHrs > 0 Then
TempDate1 = Format([Forms]![BalFitToFabricate]![Text51].Value, "mm-dd-yyyy")
'TempDate1 = [Forms]![BalFitToFabricate]![Text68].Value
dbs.Execute "UPDATE BalFitToFabricate " & "SET startdate = #" & TempDate1 & "# WHERE ID = " & Initrst!ID & ";"
TempDate2 = AddFinishDate(Format(TempDate1, "mm-dd-yyyy"), Initrst!ReqDays, Me.FridayOffCheckBox2)
dbs.Execute "UPDATE BalFitToFabricate " & "SET finishdate = #" & TempDate2 & "# WHERE ID = " & Initrst!ID & ";"
'TempDate1 = strSQL59 + (strSQL22 / strSQL57)
'TempDate2 = Format(TempDate1 + (Valuesrst![Total_Req_Manhours] / Valuesrst![Crew Hours]), "dd-mm-yyyy")
'dbs.Execute "UPDATE BalFitToFabricate " & "SET Finishdate = #" & TempDate2 & "# WHERE Autonum = " & Initrst!AutoNum & ";"
dbs.Execute "UPDATE BalFitToFabricate " & "SET Used = True WHERE ID = " & Initrst!ID & ";"
End If
Initrst.MoveNext
'Autonumrst.MoveNext
Else
GoTo ExitLoop1
End If
Loop
ExitLoop1:
'MsgBox rst!Ord_No & " " & rst2!Ord_No
dbs.Execute "UPDATE BalFitToFabricate " & "SET Used = False;"
TotalDailyHrs = Forms("BalFitToFabricate").Text49.Value
TempDailyHours = TotalDailyHrs
'Second Loop
Do Until rstClient.EOF = True
'Counter = Counter + 1
'i = rstClient!Ord_No
'If rstClient.Fields("Duration") <> "" Then
' DurationTotal = DurationTotal + rstClient.Fields("Duration")
'FieldArray(Counter) = rstClient.Fields("End")
'End If
'If DurationTotal >= 15 Then
If TempDailyHours <= TotalDailyHrs Then
'If rstClient!Used = False Then
strSQL3 = "SELECT * FROM Table2 where Finishdate is null;"
Set Valuesrst = CurrentDb.OpenRecordset(strSQL3)
Valuesrst.Requery
'Counter = rst2.RecordCount
Dim temp22 As Integer
temp22 = rst.RecordCount
rst.Requery
rst2.Requery
If rst2.RecordCount <= 0 Then
GoTo ExitLoop2
End If
LowDate1 = "#" & rst!FinishDate & "#"
'LowDate2 = "#" & Valuesrst!finishdate & "#"
'End If
''Set dbs = OpenDatabase("database41.accdb")
TempDate1 = Format(rst!FinishDate, "mm-dd-yyyy")
dbs.Execute "UPDATE BalFitToFabricate " & "SET Used = true WHERE ID = " & rst!ID & ";"
dbs.Execute "UPDATE BalFitToFabricate " & "SET startdate = #" & TempDate1 & "# WHERE ID = " & rst2!ID & ";"
'TempDate1 = Format([Forms]![BalFitToFabricate]![Text59].Value + ([Forms]![BalFitToFabricate]![Text22].Value / [Forms]![BalFitToFabricate]![Text57].Value), "dd-mm-yyyy")
'TempDate1 = Format(Valuesrst![StartDate] + (Valuesrst![Total_Req_Manhours] / Valuesrst![Crew Hours]), "dd-mm-yyyy")
'dbs.Execute "UPDATE BalFitToFabricate " & "SET Finishdate = #" & TempDate1 & "# WHERE Autonum = " & Valuesrst!AutoNum & ";"
TempDate2 = AddFinishDate(Format(TempDate1, "mm-dd-yyyy"), rst!ReqDays, Me.FridayOffCheckBox2)
dbs.Execute "UPDATE BalFitToFabricate " & "SET finishdate = #" & TempDate2 & "# WHERE ID = " & rst2!ID & ";"
End If
'rstClient.MoveNext
Loop
ExitLoop2:
MsgBox "Finished Scheduling " & DurationTotal & "Time: " & Time()
rstClient.Close
[Forms]![BalFitToFabricate].Refresh
End Sub
This is not that easy, if you don't work round the clock. I have an old function that takes off-hours and weekends in consideration, though not holidays:
Public Function WorkhourAdd( _
ByVal datDateStart As Date, _
ByVal intHours As Integer) _
As Date
' Purpose: Add number of working hours to date datDateStart.
' Assumes: 5 working days per week. Adjust cbytWorkdaysOfWeek for other values.
' First workday is Monday.
' Weekend is up to and including Sunday.
' Limitation: Does not count for public holidays.
' May be freely used and distributed.
'
' 2011-01-15. Gustav Brock, Cactus Data ApS, Copenhagen
' Specify begin and end time of daily working hours.
Const cdatWorkTimeStart As Date = #8:00:00 AM#
Const cdatWorkTimeStop As Date = #4:00:00 PM#
Const cbytWorkdaysOfWeek As Byte = 5
Dim intCount As Integer
Dim datDateEnd As Date
datDateEnd = datDateStart
While intCount < intHours
datDateEnd = DateAdd("h", 1, datDateEnd)
If Weekday(datDateEnd, vbMonday) <= cbytWorkdaysOfWeek Then
If DateDiff("h", cdatWorkTimeStart, TimeValue(datDateEnd)) > 0 Then
If DateDiff("h", TimeValue(datDateEnd), cdatWorkTimeStop) >= 0 Then
intCount = intCount + 1
End If
End If
End If
Wend
WorkhourAdd = datDateEnd
End Function
You could modify it to check if time is within a holiday, to find finish time across holidays.
While testing my program, an error popped up saying, "Too many connections" when I tried to log in an another user.
I need to fix it so that the connections aren't left open to time out on their own, so that it runs perfectly.
Private Sub addstub()
Using connection As New MySqlConnection(connectionstring)
SQL = "SELECT count(*) from remaining_ham where Stub=#stub and Emp_No LIKE '%" & txtid.Text & "%'"
Using Command As New MySqlCommand(SQL, connection)
Command.Parameters.AddWithValue("#stub", txtclaim.Text)
Command.Parameters.AddWithValue("#claim", "CLAIMED")
Command.CommandText = SQL
connection.Open()
Dim count As Integer = Command.ExecuteScalar
If count = 1 Then
MsgBox("PROCESSING")
Using connection2 As New MySqlConnection(connectionstring)
SQL = "Select count(*) from remaining_ham where status='CLAIMED' and Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using command2 As New MySqlCommand(SQL, connection)
connection2.Open()
Dim i1 As Integer = command2.ExecuteScalar()
If i1 = 1 Then
MsgBox("ALREADY CLAIMED")
Else
Using connection3 As New MySqlConnection(connectionstring)
SQL = "Select Stub,Total,Brickham,Jamon,Fiesta,status from remaining_ham where Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using myAdapter As New MySqlDataAdapter(SQL, connection)
Dim table = New DataSet
myAdapter.Fill(table)
txtbrick.Text = table.Tables(0).Rows(0)("Brickham").ToString
txtjamon.Text = table.Tables(0).Rows(0)("Jamon").ToString
txtfiesta.Text = table.Tables(0).Rows(0)("Fiesta").ToString
txttotal.Text = table.Tables(0).Rows(0)("Total").ToString
If MsgBox("ARE YOU SURE?" + Environment.NewLine + "Stub No: " + txtid.Text + Environment.NewLine + "Brickham: " + txtbrick.Text + Environment.NewLine + "Jamon De Bola: " + txtjamon.Text + Environment.NewLine + "Fiesta Ham: " + txtfiesta.Text, MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
'MsgBox("TAMA")
jam = CDbl(txtjamon.Text)
rmham = CDbl(txtremjamon.Text)
txtremjamon.Text = (rmham - jam).ToString
Dim dbjam = Format(CDbl(txtremjamon.Text), "#,###")
If dbjam = "" Then
dbjam = 0
End If
brk = CDbl(txtbrick.Text)
rembrk = CDbl(txtrembrick.Text)
txtrembrick.Text = (rembrk - brk).ToString
Dim dbbrick = Format(CDbl(txtrembrick.Text), "#,###")
If dbbrick = "" Then
dbbrick = 0
End If
fiesta = CDbl(txtfiesta.Text)
rmfiesta = CDbl(txtremfiesta.Text)
txtremfiesta.Text = (rmfiesta - fiesta).ToString
Dim dbfiesta = Format(CDbl(txtremfiesta.Text), "#,###")
If dbfiesta = "" Then
dbfiesta = 0
End If
total = CDbl(txttotal.Text)
rmtotal = CDbl(txtremtotal.Text)
txtremtotal.Text = (rmtotal - total).ToString
Dim dbtotal = Format(CDbl(txtremtotal.Text), "#,###")
If dbtotal = "" Then
dbtotal = 0
End If
Using connection4 As New MySqlConnection(connectionstring)
SQL = "UPDATE order_ham SET rem_brick='" & dbbrick & "', rem_jam='" & dbjam & "', rem_fiesta='" & dbfiesta & "', rem_total='" & dbtotal & "' where Emp_No=" & txtid.Text & " "
Using command3 As New MySqlCommand(SQL, connection4)
connection4.Open()
Dim i As Integer = command3.ExecuteNonQuery
If i = 0 Then
MsgBox("WRONG")
Exit Sub
Else
' MsgBox("RIGHT")
Using connection5 As New MySqlConnection(connectionstring)
Dim date1 As Date = Date.Today
SQL = "UPDATE remaining_ham SET status='CLAIMED',ddate='" & DateTime.Now & "' where Stub='" + txtclaim.Text + "' and Emp_No LIKE '%" + txtid.Text + "%' "
Using command4 As New MySqlCommand(SQL, connection5)
connection5.Open()
Dim a As Integer = command4.ExecuteNonQuery
connection5.Close()
If a = 0 Then
MsgBox("not claim: ERROR ")
Exit Sub
Else
MsgBox("SUCCESS")
Using da As New MySqlDataAdapter(SQL, connection5)
Dim dt As New DataTable
da.Fill(dt)
MetroGrid1.DataSource = Nothing
MetroGrid1.Rows.Clear()
MetroGrid3.DataSource = Nothing
MetroGrid3.Rows.Clear()
loadRemainingHam()
remainingorder()
txtclaim.Focus()
End Using
End If
End Using
End Using
End If
End Using
End Using
Else
MsgBox("CANCELLED")
End If
End Using
End Using
End If
End Using
End Using
Else
MsgBox("ERROR")
End If
End Using
End Using
End Sub
Thank you for those who will answer.
You can perform multiple commands/actions with 1 connection.
You could try something like this:
Dim connection As New MySqlConnection(connectionstring)
connection.Open()
Dim SQL as String = "SELECT count(*) from remaining_ham where Stub=#stub and Emp_No LIKE '%" & txtid.Text & "%'"
Using ObjCommand As New MySqlCommand(SQL, connection)
ObjCommand.Parameters.AddWithValue("#stub", txtclaim.Text)
ObjCommand.Parameters.AddWithValue("#claim", "CLAIMED")
ObjCommand.CommandText = SQL
Dim count As Integer = Command.ExecuteScalar
If count = 1 Then
MsgBox("PROCESSING")
SQL = "Select count(*) from remaining_ham where status='CLAIMED' and Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using ObjCommand2 As New MySqlCommand(SQL, connection)
Dim i1 As Integer = command2.ExecuteScalar()
If i1 = 1 Then
MsgBox("ALREADY CLAIMED")
Else
SQL = "Select Stub,Total,Brickham,Jamon,Fiesta,status from remaining_ham where Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using myAdapter As New MySqlDataAdapter(SQL, connection)
//code here
End Using
End If
End Using
End If
End Using
connection.Close()
connection.Dispose()
What is the database of this program? can you please add ;pooling=false at the end of your mysqlconnection like this
server=localhost;user=root;database=world;port=3306;password=******;pooling=false
and try it
You have way to many queries inside of queries. Try to remove as much as possible. Here's an example with the first one.
You should close the connections as soon as possible.
Private Sub addstub()
'*** GET THE COUNT, CLOSE THE CONNECTION, NOT NEEDED ANYMORE.
Dim count As Integer
Using connection As New MySqlConnection(connectionstring)
SQL = "SELECT count(*) from remaining_ham where Stub=#stub and Emp_No LIKE '%" & txtid.Text & "%'"
Using Command As New MySqlCommand(SQL, connection)
Command.Parameters.AddWithValue("#stub", txtclaim.Text)
Command.Parameters.AddWithValue("#claim", "CLAIMED")
Command.CommandText = SQL
connection.Open()
count = Command.ExecuteScalar
End Using
End Using
If count = 1 Then
MsgBox("PROCESSING")
Using connection2 As New MySqlConnection(connectionstring)
SQL = "Select count(*) from remaining_ham where status='CLAIMED' and Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using command2 As New MySqlCommand(SQL, connection)
connection2.Open()
Dim i1 As Integer = command2.ExecuteScalar()
If i1 = 1 Then
MsgBox("ALREADY CLAIMED")
Else
Using connection3 As New MySqlConnection(connectionstring)
SQL = "Select Stub,Total,Brickham,Jamon,Fiesta,status from remaining_ham where Stub='" & txtclaim.Text & "' and Emp_No LIKE'%" & txtid.Text & "%' "
Using myAdapter As New MySqlDataAdapter(SQL, connection)
Dim table = New DataSet
myAdapter.Fill(table)
txtbrick.Text = table.Tables(0).Rows(0)("Brickham").ToString
txtjamon.Text = table.Tables(0).Rows(0)("Jamon").ToString
txtfiesta.Text = table.Tables(0).Rows(0)("Fiesta").ToString
txttotal.Text = table.Tables(0).Rows(0)("Total").ToString
If MsgBox("ARE YOU SURE?" + Environment.NewLine + "Stub No: " + txtid.Text + Environment.NewLine + "Brickham: " + txtbrick.Text + Environment.NewLine + "Jamon De Bola: " + txtjamon.Text + Environment.NewLine + "Fiesta Ham: " + txtfiesta.Text, MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
'MsgBox("TAMA")
jam = CDbl(txtjamon.Text)
rmham = CDbl(txtremjamon.Text)
txtremjamon.Text = (rmham - jam).ToString
Dim dbjam = Format(CDbl(txtremjamon.Text), "#,###")
If dbjam = "" Then
dbjam = 0
End If
brk = CDbl(txtbrick.Text)
rembrk = CDbl(txtrembrick.Text)
txtrembrick.Text = (rembrk - brk).ToString
Dim dbbrick = Format(CDbl(txtrembrick.Text), "#,###")
If dbbrick = "" Then
dbbrick = 0
End If
fiesta = CDbl(txtfiesta.Text)
rmfiesta = CDbl(txtremfiesta.Text)
txtremfiesta.Text = (rmfiesta - fiesta).ToString
Dim dbfiesta = Format(CDbl(txtremfiesta.Text), "#,###")
If dbfiesta = "" Then
dbfiesta = 0
End If
total = CDbl(txttotal.Text)
rmtotal = CDbl(txtremtotal.Text)
txtremtotal.Text = (rmtotal - total).ToString
Dim dbtotal = Format(CDbl(txtremtotal.Text), "#,###")
If dbtotal = "" Then
dbtotal = 0
End If
Using connection4 As New MySqlConnection(connectionstring)
SQL = "UPDATE order_ham SET rem_brick='" & dbbrick & "', rem_jam='" & dbjam & "', rem_fiesta='" & dbfiesta & "', rem_total='" & dbtotal & "' where Emp_No=" & txtid.Text & " "
Using command3 As New MySqlCommand(SQL, connection4)
connection4.Open()
Dim i As Integer = command3.ExecuteNonQuery
If i = 0 Then
MsgBox("WRONG")
Exit Sub
Else
' MsgBox("RIGHT")
Using connection5 As New MySqlConnection(connectionstring)
Dim date1 As Date = Date.Today
SQL = "UPDATE remaining_ham SET status='CLAIMED',ddate='" & DateTime.Now & "' where Stub='" + txtclaim.Text + "' and Emp_No LIKE '%" + txtid.Text + "%' "
Using command4 As New MySqlCommand(SQL, connection5)
connection5.Open()
Dim a As Integer = command4.ExecuteNonQuery
connection5.Close()
If a = 0 Then
MsgBox("not claim: ERROR ")
Exit Sub
Else
MsgBox("SUCCESS")
Using da As New MySqlDataAdapter(SQL, connection5)
Dim dt As New DataTable
da.Fill(dt)
MetroGrid1.DataSource = Nothing
MetroGrid1.Rows.Clear()
MetroGrid3.DataSource = Nothing
MetroGrid3.Rows.Clear()
loadRemainingHam()
remainingorder()
txtclaim.Focus()
End Using
End If
End Using
End Using
End If
End Using
End Using
Else
MsgBox("CANCELLED")
End If
End Using
End Using
End If
End Using
End Using
Else
MsgBox("ERROR")
End If
End Sub
The best thing you could do would be to put each query in a function. Also, parametrize everything!
Private Function GetClaimCount(ByVal id As String, ByVal claim As String) As Integer
Dim count As Integer = 0
Using connection As New MySqlConnection(connectionstring)
' id should be a parameter!!
SQL = "SELECT count(*) from remaining_ham where Stub=#stub and Emp_No LIKE '%" & id & "%'"
Using Command As New MySqlCommand(SQL, connection)
Command.Parameters.AddWithValue("#stub", claim)
Command.Parameters.AddWithValue("#claim", "CLAIMED")
Command.CommandText = SQL
connection.Open()
count = Command.ExecuteScalar
End Using
End Using
Return count
End Function
Private Sub addstub()
Dim count As Integer = GetClaimCount(txtid.Text, txtclaim.Text)
If count = 1 Then
MsgBox("PROCESSING")
' ...
Else
MsgBox("ERROR")
End If
End Sub
I am pulling data from database into a recordset then converting to array and then writing to a CSV.
In the database all date values are stored as timestamps in this format.
2016-05-04 08:00:00.000000
But when I write to the CSV file the timestamp does not include the milliseconds.
Anyone know how to preserve the milliseconds?
Does the data in the recordset include the milliseconds?
On Error Resume Next
Dim sPassword
Dim sUserID
Dim sDefaultLib
Dim sSystem
Dim cs
Dim rc
Dim objIEDebugWindow
sDefaultLib = *library*
sUserID = *userid*
sPassword = *password*
sSystem = *system*
cs = *connectionString*
Set con = CreateObject("ADODB.Connection")
Set data = CreateObject("ADODB.Recordset")
con.Open cs, sUserID, sPassword
rc = con.State
If (rc = 1) Then
strQuery = "SELECT * FROM Library.Table FETCH FIRST 15 ROWS ONLY FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.Open strQuery, con
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Dim theYear
Dim theMonth
Dim theDay
Dim mDate
mDate = Date()
theYear = DatePart("yyyy", mDate)
theMonth = Right(String(2, "0") & DatePart("m", mDate), 2)
theDate = Right(String(2, "0") & DatePart("d", mDate), 2)
mDate = theYear & theMonth & theDate
Set csvFile = filsSysObj.OpenTextFile("C:\SampleFile_" & mDate & ".csv", 8, True)
columnCount = data.Fields.Count
Set i = 0
For Each field In data.Fields
i= i + 1
If (i <> columnCount) Then
csvFile.Write Chr(34) & field.Name & Chr(34) & ","
Else
csvFile.Write Chr(34) & field.Name & Chr(34)
End If
Next
csvFile.Write vbNewLine
End If
rowCount = data.RecordCount
row = 0
Dim row
Dim column
Dim resultsArray
Dim dateArray
resultsArray = data.GetRows
debug "hi"
i = 0
Do Until i>5
MsgBox(i)
i = i + 1
'debug "in"
'Dim value
'Dim dArray()
'debug "in"
'value = Chr(34) & CStr(data.Fields(17).Value) & Chr(34) & ","
'dArray = additem(dArray, value)
'data.MoveNext
'dateArray = dArray
Loop
debug "out"
For row = 0 To UBound(resultsArray, 2)
For column = 0 To UBound(resultsArray, 1)
If row = UBound(resultsArray, 2) And column = UBound(resultsArray, 1) Then
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34)
Else
If column = 0 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
ElseIf column = 19 Then
csvFile.Write Chr(34) & FormatDateTime(resultsArray(column, row),4) & Chr(34) & ","
ElseIf column = 18 Then
csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
'ElseIf column = 17 Then
'csvFile.Write Chr(34) & formatDate(resultsArray(column, row)) & Chr(34) & ","
Else
csvFile.Write Chr(34) & resultsArray(column, row) & Chr(34) & ","
End If
End If
Next
csvFile.Write vbNewLine
Next
csvFile.close
'----------------------Helper Functions are below-----------------------------
Sub Debug(myText)
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject(objIEDebugWindow) Then
Set objIEDebugWindow = CreateObject("InternetExplorer.Application")
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
Function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
End Function
The only field I am having issues with is field 17 of the recordset.
It is a timestamp datatype from a DB2 database.
The issue was the format is a timestamp in DB2 database. When i pull into a recordset it loses the milliseconds. My solution was to modify the query to add an extra row that pulls in only milliseconds and then later concatenate that back to the date. Please see below. Thanks for everyones help.
if(rc = 1) then
logFile.write FormatDateTime(Now(), 3) & ": Database connection successful" & vbNewLine
logFile.write FormatDateTime(Now(), 3) &": Default Library: " & sDefaultLib & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": Signed into server as: " & sUserID & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": System: " & sSystem & vbNewLine
strQuery = "SELECT ws_date, groupcd, userid, firstname, lastname, clientcd, unitcd, categorycd, category, activity, wrktype, subwrktype, step_begin, step_end, report_indicator, report_indicator, count, event_dattim, key_date, key_time, key_milsec, microsecond(event_dattim) FROM *Library.Name* FOR READ ONLY WITH UR"
data.CursorLocation = adUseClient
data.open strQuery, con
if data.EOF then
logFile.write FormatDateTime(Now(), 3) & ": The query returned no data"
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". There was no worksteps file created. ----------------" & vbNewLine
logFile.close
end if
columnCount = data.Fields.Count
columnCount = columnCount - 1
Set filsSysObj = CreateObject("Scripting.FileSystemObject")
Set csvFile = filsSysObj.OpenTextFile("C:\VBScript\Dailys\" & fname, 8, True)
set i = 0
for each field in data.Fields
i= i + 1
if i < columnCount then
csvFile.Write chr(34) & field.name & chr(34) & ","
elseif i = columnCount then
csvFile.Write chr(34) & field.name & chr(34)
else
exit for
end if
next
csvFile.Write vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": Database connection was unsuccessful. Database Connection Return Code: " & rc
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logFile.close
csvfile.close
wscript.quit
end if
dim row
dim column
dim resultsArray
resultsArray = data.GetRows
dim arrayRows
arrayRows = ubound(resultsArray, 2)
if arrayRows <> 0 then
logFile.write FormatDateTime(Now(), 3) & ": " & (arrayRows + 1) & " rows were successfully read into the array for file " & fname & vbnewline
for row = 0 to UBound(resultsArray, 2)
for column = 0 to (UBound(resultsArray, 1) - 1)
if row = Ubound(resultsArray, 2) and column = (ubound(resultsArray, 1) - 1) then
csvFile.Write chr(34) & resultsArray(column, row) & chr(34)
else
if column = 0 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 19 then
csvFile.Write chr(34) & FormatDateTime(resultsArray(column, row),4) & chr(34) & ","
elseif column = 18 then
csvFile.Write chr(34) & formatDate(resultsArray(column, row)) & chr(34) & ","
elseif column = 17 then
Dim fDate
fDate = formatDate(resultsArray(column, row)) & " " & FormatDateTime(resultsArray(column, row),4) & ":" & second(resultsArray(column,row)) & "." & resultsArray((ubound(resultsArray, 1)), row)
csvFile.Write chr(34) & fDate & chr(34) & ","
else
csvFile.Write chr(34) & resultsArray(column, row) & chr(34) & ","
end if
end if
next
csvFile.Write vbNewLine
next
logfile.write FormatDateTime(Now(), 3) & ": " & (row) & " rows have been written to " & fname &vbNewLine
else
logFile.write FormatDateTime(Now(), 3) & ": There was no data in the query results array for file " & fname & vbNewLine
logFile.write FormatDateTime(Now(), 3) & ": ---------------- The script DailyWorkstepReport.vbs file was abended at " & Now() &". ----------------" & vbNewLine
logfile.close
csvfile.close
wscript.quit
end if
csvFile.close
logfile.write "---------------- DailyWorkstepReport.vbs script successfully ended at " & Now() & "----------------" & vbNewLine
logfile.close
wscript.quit
REM ----------------------Helper Functions are below-----------------------------
Sub Debug( myText )
'Dim objIEDebugWindow must be defined globally
'Call like this "Debug variableName"
'Uncomment the next line to turn off debugging
'Exit Sub
If Not IsObject( objIEDebugWindow ) Then
Set objIEDebugWindow = CreateObject( "InternetExplorer.Application" )
objIEDebugWindow.Navigate "about:blank"
objIEDebugWindow.Visible = True
objIEDebugWindow.ToolBar = False
objIEDebugWindow.Width = 200
objIEDebugWindow.Height = 300
objIEDebugWindow.Left = 10
objIEDebugWindow.Top = 10
Do While objIEDebugWindow.Busy
WScript.Sleep 100
Loop
objIEDebugWindow.Document.Title = "IE Debug Window"
objIEDebugWindow.Document.Body.InnerHTML = "<b>" & Now & "</b></br>"
End If
objIEDebugWindow.Document.Body.InnerHTML = objIEDebugWindow.Document.Body.InnerHTML & myText & "<br>" & vbCrLf
End Sub
function formatDate(sDate)
Dim theYear
Dim theMonth
Dim theDay
Dim formattedDate
theYear = Year(sDate)
theMonth = Right(String(2,"0") & DatePart("m", sDate),2)
theDay = Right(String(2,"0") & DatePart("d", sDate),2)
formattedDate = theYear & "-" & theMonth & "-" & theDate
formatDate = formattedDate
end function
I want to run a script in my macro multiple times by changing variable values.
Below is an example of my code that I run for one value.
The line of code I would like to change is
sScript = sScript + "where m.outletid in ('" & sOutletId & "') " & vbCrLf
Sometime I want the where clause to be
where m.outletid in ('12314')
or
where m.chainid in ('411')...
Code:
Sub Report()
Dim sScript As String
Dim sServer As String
Dim sDatabase As String
Dim sTransTable As String
Dim iVal As Integer
Dim iReturnVal As Integer
Dim SheetExists As Worksheet
Dim WK_SHEET As String
sServer = Trim(UserForm1.txtServer.Value)
sDatabase = Trim(UserForm1.txtDatabase.Value)
sTransTable = Trim(UserForm1.txtTransTable.Value)
For Each SheetExists In Worksheets
If SheetExists.Name = ("Report") Then
Application.DisplayAlerts = False
Sheets("Report").Delete
Application.DisplayAlerts = True
Exit For
End If
Next SheetExists
Worksheets.Add after:=Sheets("Sheet1")
ActiveSheet.Name = ("Report")
WK_SHEET = "Report"
Sheets(WK_SHEET).Select
sOutletId = "12314"
sScript = "Select top 10 m.CustNumber, m.Name, sum(t.Transvalue) " & vbCrLf
sScript = sScript + "from " & sTransTable & " t " & vbCrLf
sScript = sScript + "where m.outletid in ('" & sOutletId & "') " & vbCrLf
sScript = sScript + "Group by m.CustNumber, m.Name " & vbCrLf
sScript = sScript + "order by sum(t.Transvalue)Desc " & vbCrLf
iReply = MsgBox(Prompt:="Do you wish to continue with the following script for Top 10 Customers?" + sScript + "", _
Buttons:=vbYesNo, Title:="Run MACRO Top 10 Reports")
If iReply = vbNo Then
End
End If
iVal = execute_sql_select(WK_SHEET, 2, 1, sServer, sDatabase, sScript)
Sheets(WK_SHEET).Name = "Outlet" & sOutletId & "Top 10 by Spend"
Now I would like to re run the above with OutletId 12315...how can I do this? Do I use some sort of loop?
You can keep list of OutletId into Array. Then get each OutletId from Array (for loop) and execute your sql script.
Pseudu code
Array listOutid = new Array[12,13,14,15];
for(int idx = 0; idx < listOutid.Length; idx++)
{
var OutletId = listOutid[idx];
//put ur sql statement and execute here..
}