I'm trying to modify the last character of a column depending on what this character is. So far, the best method I've come to is to use the Update Case with the Right() function, but it doesn't work, when I execute it I've got an error telling me I'm missing an operator and I can't figure out how to fix it. Here's my code :
UPDATE Import
SET MONTANT =
(
CASE WHEN Right([MONTANT], 1)='é' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '0'
WHEN Right([MONTANT], 1)='{' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '0'
WHEN Right([MONTANT], 1)='A' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '1'
WHEN Right([MONTANT], 1)='B' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '2'
WHEN Right([MONTANT], 1)='C' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '3'
WHEN Right([MONTANT], 1)='D' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '4'
WHEN Right([MONTANT], 1)='E' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '5'
WHEN Right([MONTANT], 1)='F' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '6'
WHEN Right([MONTANT], 1)='G' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '7'
WHEN Right([MONTANT], 1)='H' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '8'
WHEN Right([MONTANT], 1)='I' THEN Left([MONTANT], LEN([MONTANT]) - 1) & '9'
WHEN Right([MONTANT], 1)='è' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '0'
WHEN Right([MONTANT], 1)='}' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '0'
WHEN Right([MONTANT], 1)='J' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '1'
WHEN Right([MONTANT], 1)='K' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '2'
WHEN Right([MONTANT], 1)='L' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '3'
WHEN Right([MONTANT], 1)='M' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '4'
WHEN Right([MONTANT], 1)='N' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '5'
WHEN Right([MONTANT], 1)='O' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '6'
WHEN Right([MONTANT], 1)='P' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '7'
WHEN Right([MONTANT], 1)='Q' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '8'
WHEN Right([MONTANT], 1)='R' THEN '-' & Left([MONTANT],LEN([MONTANT])-1) & '9'
ELSE MONTANT
END
)
I already tried a few fixes : Using LENGTH instead of LEN doesn't do a thing, using the syntax :
CASE Right([MONTANT], 1) WHEN 'é' THEN
Following your pieces of advice, i tried the 2 other forms : Using IIF and Using Switch as follows :
UPDATE Import
SET MONTANT = SWITCH(
RIGHT(MONTANT, 1)='é', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '0',
RIGHT(MONTANT, 1)='{', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '0',
RIGHT(MONTANT, 1)='A', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '1',
RIGHT(MONTANT, 1)='B', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '2',
RIGHT(MONTANT, 1)='C', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '3',
RIGHT(MONTANT, 1)='D', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '4',
RIGHT(MONTANT, 1)='E', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '5',
RIGHT(MONTANT, 1)='F', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '6',
RIGHT(MONTANT, 1)='G', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '7',
RIGHT(MONTANT, 1)='H', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '8',
RIGHT(MONTANT, 1)='I', LEFT(MONTANT, LENGTH(MONTANT) - 1) & '9',
RIGHT(MONTANT, 1)='è', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '0',
RIGHT(MONTANT, 1)='}', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '0',
RIGHT(MONTANT, 1)='J', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '1',
RIGHT(MONTANT, 1)='K', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '2',
RIGHT(MONTANT, 1)='L', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '3',
RIGHT(MONTANT, 1)='M', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '4',
RIGHT(MONTANT, 1)='N', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '5',
RIGHT(MONTANT, 1)='O', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '6',
RIGHT(MONTANT, 1)='P', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '7',
RIGHT(MONTANT, 1)='Q', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '8',
RIGHT(MONTANT, 1)='R', '-' & LEFT(MONTANT,LENGTH(MONTANT)-1) & '9'
)
The issue being that Access also tells me that it's too complicated, maybe i should try doing it in two separate requests... I'm still opened to new ideas that might work
You can use Switch instead of CASE .. WHEN
A problem that occurs is that Access SQL can't handle functions with a large number of arguments. This is easily resolved by splitting it into pieces:
UPDATE Import
SET MONTANT =
SWITCH(
RIGHT(MONTANT, 1)='é', LEFT(MONTANT, LEN(MONTANT) - 1) & '0',
RIGHT(MONTANT, 1)='{', LEFT(MONTANT, LEN(MONTANT) - 1) & '0',
RIGHT(MONTANT, 1)='A', LEFT(MONTANT, LEN(MONTANT) - 1) & '1',
RIGHT(MONTANT, 1)='B', LEFT(MONTANT, LEN(MONTANT) - 1) & '2',
RIGHT(MONTANT, 1)='C', LEFT(MONTANT, LEN(MONTANT) - 1) & '3',
RIGHT(MONTANT, 1)='D', LEFT(MONTANT, LEN(MONTANT) - 1) & '4',
True, SWITCH(
RIGHT(MONTANT, 1)='E', LEFT(MONTANT, LEN(MONTANT) - 1) & '5',
RIGHT(MONTANT, 1)='F', LEFT(MONTANT, LEN(MONTANT) - 1) & '6',
RIGHT(MONTANT, 1)='G', LEFT(MONTANT, LEN(MONTANT) - 1) & '7',
RIGHT(MONTANT, 1)='H', LEFT(MONTANT, LEN(MONTANT) - 1) & '8',
RIGHT(MONTANT, 1)='I', LEFT(MONTANT, LEN(MONTANT) - 1) & '9',
True, SWITCH(
RIGHT(MONTANT, 1)='è', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '0',
RIGHT(MONTANT, 1)='}', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '0',
RIGHT(MONTANT, 1)='J', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '1',
RIGHT(MONTANT, 1)='K', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '2',
RIGHT(MONTANT, 1)='L', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '3',
RIGHT(MONTANT, 1)='M', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '4',
True, SWITCH(
RIGHT(MONTANT, 1)='N', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '5',
RIGHT(MONTANT, 1)='O', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '6',
RIGHT(MONTANT, 1)='P', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '7',
RIGHT(MONTANT, 1)='Q', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '8',
RIGHT(MONTANT, 1)='R', '-' & LEFT(MONTANT,LEN(MONTANT)-1) & '9',
True, MONTANT
))))
I'm also using the Switch statements to split this into chunks, if you go for the maximum number of arguments per switch you can get away with less Switch functions.
In Access there is no CASE support, but you can use IIF.
I tried to put all your conditions in nested IIFs but Access found the whole statement too complicated.
I tried to follow your logic and zipped the code like this:
UPDATE Import
SET MONTANT =
IIF(Right([MONTANT], 1) IN ('é', 'è', '{', '}'), IIF(Right([MONTANT], 1) IN ('è', '}'), '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '0',
IIF(Right([MONTANT], 1) IN ('A', 'J'), IIF(Right([MONTANT], 1) = 'J', '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '1',
IIF(Right([MONTANT], 1) IN ('B', 'K'), IIF(Right([MONTANT], 1) = 'K', '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '2',
IIF(Right([MONTANT], 1) IN ('C', 'L'), IIF(Right([MONTANT], 1) = 'L', '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '3',
IIF(Right([MONTANT], 1) IN ('D', 'M'), IIF(Right([MONTANT], 1) = 'M', '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '4',
IIF(Right([MONTANT], 1) IN ('E', 'N'), IIF(Right([MONTANT], 1) = 'N', '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '5',
IIF(Right([MONTANT], 1) IN ('F', 'O'), IIF(Right([MONTANT], 1) = 'O', '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '6',
IIF(Right([MONTANT], 1) IN ('G', 'P'), IIF(Right([MONTANT], 1) = 'P', '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '7',
IIF(Right([MONTANT], 1) IN ('H', 'Q'), IIF(Right([MONTANT], 1) = 'Q', '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '8',
IIF(Right([MONTANT], 1) IN ('I', 'R'), IIF(Right([MONTANT], 1) = 'R', '-', '') & Left([MONTANT], LEN([MONTANT]) - 1) & '9', MONTANT
))))))))))
Since I could not try it with actual data, I only tested its validity.
So try with caution.
If your data set is large and you're interseted in creating a maintainable solution, I would suggest the following:
Add two fields to your Import table:
UpdateChar as Short Text
RemainderString as Short Text
Update the field UpdateChar to the Right([MONTANT], 1)
Update the field RemainderString to Left([MONTANT], LEN([MONTANT]) - 1)
Create a new table which contains the update pairs, with two fields:
FromChar as Short Text (this will contain the chars: é, {, }, etc.)
ToChar as Short Text (this will match with the chars: 0, 1, 2, ...9)
Then in a separate Update query, link the UpdateChar field from the Import table to the FromChar field in the update pairs table. Then update the Montant field with the string concatenation of RemainderString(Import table) and ToChar(Update pairs table)
Although this involves multiple steps, I find it a much cleaner solution. Especially if you need to add additional characters in the future.
Related
I am writing a user form that has the simple function of moving stock from one BIN to another. My stock transactions are all in a single table. I have created an sql view that gives me stock totals by code and location.
I can then search current location and bring up all the stock in a listbox to view. I then scan the second location.
The macro I am working on is the 'Record' command.
It's objective is to create the following sql string/s based on the listbox results.
INSERT INTO db.tblstocktrans (`IDtblStocktrans`, `DateTime`, `STCode`, `StockLocation`, `MovementType`, `UnitType`, `Units`, `Attachment`, `keyPersonnel`) VALUES ('1751', '2022-01-11 00:00:00', '000238', 'D-01-40', 'MoveOut', 'Unit', '10', ?, '28');
INSERT INTO db.tblstocktrans (`IDtblStocktrans`, `DateTime`, `STCode`, `StockLocation`, `MovementType`, `UnitType`, `Units`, `Attachment`, `keyPersonnel`) VALUES ('1752', '2022-01-11 00:00:00', '001063', 'D-01-40', 'MoveOut', 'Unit', '9', ?, '28');
INSERT INTO db.tblstocktrans (`IDtblStocktrans`, `DateTime`, `STCode`, `StockLocation`, `MovementType`, `UnitType`, `Units`, `Attachment`, `keyPersonnel`) VALUES ('1753', '2022-01-11 00:00:00', '001290', 'D-01-40', 'MoveOut', 'Unit', '8', ?, '28');
INSERT INTO db.tblstocktrans (`IDtblStocktrans`, `DateTime`, `STCode`, `StockLocation`, `MovementType`, `UnitType`, `Units`, `Attachment`, `keyPersonnel`) VALUES ('1754', '2022-01-11 00:00:00', '001111', 'D-01-40', 'MoveOut', 'Unit', '7', ?, '28');
INSERT INTO db.tblstocktrans (`IDtblStocktrans`, `DateTime`, `STCode`, `StockLocation`, `MovementType`, `UnitType`, `Units`, `Attachment`, `keyPersonnel`) VALUES ('1751', '2022-01-11 00:00:00', '000238', 'D-02-40', 'MoveIn', 'Unit', '10', ?, '28');
INSERT INTO db.tblstocktrans (`IDtblStocktrans`, `DateTime`, `STCode`, `StockLocation`, `MovementType`, `UnitType`, `Units`, `Attachment`, `keyPersonnel`) VALUES ('1752', '2022-01-11 00:00:00', '001063', 'D-02-40', 'MoveIn', 'Unit', '9', ?, '28');
INSERT INTO db.tblstocktrans (`IDtblStocktrans`, `DateTime`, `STCode`, `StockLocation`, `MovementType`, `UnitType`, `Units`, `Attachment`, `keyPersonnel`) VALUES ('1753', '2022-01-11 00:00:00', '001290', 'D-02-40', 'MoveIn', 'Unit', '8', ?, '28');
INSERT INTO db.tblstocktrans (`IDtblStocktrans`, `DateTime`, `STCode`, `StockLocation`, `MovementType`, `UnitType`, `Units`, `Attachment`, `keyPersonnel`) VALUES ('1754', '2022-01-11 00:00:00', '001111', 'D-02-40', 'MoveIn', 'Unit', '7', ?, '28');
As each BIN location can have multiple and variable number of product lines I wanted my code to loop through the list and update the database line by line.
This is the best I have come up with but can't get it to work.
Private Sub cmdRecord_Click()
Dim i As Integer
For i = 0 To ListBox1.ListCount - 1
Dim SUnits As Integer
Dim STCode1 As String
Dim UnitType1
On Error GoTo ErrorHandler
SUnits = ListBox1.List(i, 4).Value
STCode1 = ListBox1.List(i, 2).Value
Dim FindRow
Dim cRow As String
cRow = STCode1
Set FindRow = Sheets("tblStock").Range("$A:$A").Find(What:=cRow, LookIn:=xlValues)
UnitType1 = FindRow.Offset(0, 23)
Dim objConn As Object
Set objConn = CreateObject("ADODB.Connection")
Dim StrA As String
Dim Str1 As String
Dim Str2 As String
Dim Str3A As String
Dim Str3B As String
Dim Str4A As String
Dim Str4B As String
Dim Str5 As String
Dim Str6A As String
Dim Str6B As String
Dim Str7 As String
StrA = "INSERT INTO tblstocktrans" & _
" (DateTime,STCode,StockLocation,MovementType,UnitType,Units,keyPersonnel) Values("
Str1 = "'" & BINMove.TextBoxDate.Value & "',"
Str2 = "'" & STCode1 & "',"
Str3A = "'" & BINMove.FromBIN.Value & "',"
Str3B = "'" & BINMove.ToBIN.Value & "',"
Str4A = "'MoveOut',"
Str4A = "'MoveIn',"
Str5 = "'" & UnitType1 & "',"
Str6A = "'" & -(SUnits) & "',"
Str6B = "'" & SUnits & "',"
Str7 = "'" & BINMove.ID.Value & "'"
With objConn
.Open "Driver=MySQL ODBC 8.0 Unicode Driver;SERVER=********.mysql.database.azure.com;DATABASE=*****db;user=********;pwd=**********;PORT=3306;DFLT_BIGINT_BIND_STR=1"
.Execute StrA & _
Str1 & _
Str2 & _
Str3A & _
Str4A & _
Str5 & _
Str6A & _
Str7 & ");"
.Execute StrA & _
Str1 & _
Str2 & _
Str3B & _
Str4B & _
Str5 & _
Str6B & _
Str7 & ");"
.Close
End With
Next i
ActiveWorkbook.Connections("MySQL.db.qryrecentstocktake3").Refresh
'Message Box
Dim answer As Integer
answer = MsgBox("Stock Updated" & Chr(10) & "Do you want to move another BIN?", vbYesNo)
If answer = vbYes Then
Call cmdSearch_Click
Else
Unload Me
End If
FromBIN.SetFocus
ErrorHandler:: Exit Sub
End Sub
Thanks in Advance
I am trying to see where my issue lies with the following code.
'add data to table
CurrentDb.Execute "INSERT INTO IB Students(Student Name, Gender, IB) " & _
"VALUES (" & Me.Text6 & ",'" & Me.Combo13 & "','" & Me.Text9 & "')"
'refresh data in list on form
stdfrm.Form.Requery
Whenever I try to use the add command I get Runtime Error -3134 and it says there is a syntax error with INSERT INTO statement.
May be the name of table needs to be enclosed by brackets, and text values must be quoted:
'add data to table
sSQL = "INSERT INTO [IB Students] ([Student Name], Gender, IB) " & _
"VALUES ('" & Me.Text6 & "','" & Me.Combo13 & "','" & Me.Text9 & "')"
'print SQL for debug
Debug.print sSQL
'Run query
CurrentDb.Execute sSQL
'refresh data in list on form
stdfrm.Form.Requery
Note: if Me.Text6 (and others) is not bind to data source then you must use it as Me.Text6.Value
Edit: Maybe is a good idea check the length before run the query
When i open the immediate window it shows
INSERT INTO [IB Students] (Student Name, Gender, IB) VALUES (Micheal,'Male','2')
INSERT INTO [IB Students] (Student Name, Gender, IB) VALUES (John,'Male','1')
INSERT INTO [IB Students] ([Student Name], Gender, IB) VALUES (,'','')
INSERT INTO [IB Students] ([Student Name], Gender, IB) VALUES (,'','')
This code below will import a tab delimited file with over 255 fields into two tables. Just make sure when you design your two tables all your fields have the correct data types for the fields being imported. I originally created my tables by using Access import text file wizard. Before using the wizard I deleted the fields after 255 to create the first table and then deleted the first 255 to create the second table. Hopes this helps someone and thanks to everyone below who helped me with this project.
Public Sub ImportTextFile()
' to use the ADODB.Recordset, be sure you have a reference set to ADO
Dim rst As ADODb.Recordset
Dim rst2 As ADODb.Recordset
Dim strFile As String
Dim strInput As String
Dim varSplit As Variant
Dim intCount As Integer
Set rst = New ADODb.Recordset
Set rst2 = New ADODb.Recordset
' CHANGE THE TABLE NAME HERE
rst.Open "AppsImport1", CurrentProject.Connection, adOpenDynamic, adLockOptimistic
rst2.Open "AppsImport2", CurrentProject.Connection, adOpenDynamic, adLockOptimistic
' CHANGE THE TEXT FILE NAME AND LOCATION HERE
strFile = "G:\Home\RiskMgtReports\AutoDatabase\CreditAppExtract.txt"
Open strFile For Input As #1
Dim i As Integer
Dim n As Long
n = DMax("index_number", "fullextract_hist")
Do Until EOF(1)
' This counter is just to get to the applicable line before importing
intCount = intCount + 1
' reads the text file line by line
Line Input #1, strInput
' starts importing on the second line. Change the number to match which line you
' want to start importing from
If intCount >= 2 Then
n = n + 1
' creates a single dimension array using the split function
varSplit = Split(strInput, vbTab, , vbBinaryCompare)
' adds the record
With rst
.AddNew
.Fields(0) = n
For i = 1 To 137
If Nz(varSplit(i - 1), "") = "" Then
.Fields(i) = Null
Else
If Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Jan M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Feb M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Mar M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Apr M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "May M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Jun M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Jul M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Aug M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Sep M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Oct M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Nov M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Dec M" Then
.Fields(i) = CDate(Format(varSplit(i - 1), "mm/dd/yyyy"))
Else
.Fields(i) = varSplit(i - 1)
End If
End If
Next i
.Update
'.MoveNext 'I don't think you should need this
End With
With rst2
.AddNew
.Fields(0) = n
.Fields(1) = varSplit(0)
For i = 138 To 274
If Nz(varSplit(i - 1), "") = "" Then
.Fields(i - 136) = Null
Else
If Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Jan M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Feb M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Mar M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Apr M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "May M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Jun M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Jul M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Aug M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Sep M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Oct M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Nov M" Or Left(varSplit(i - 1), 4) & Right(Trim(varSplit(i - 1)), 1) = "Dec M" Then
.Fields(i - 136) = CDate(Format(varSplit(i - 1), "mm/dd/yyyy"))
Else
.Fields(i - 136) = varSplit(i - 1)
End If
End If
Next i
.Update
End With
End If
Loop
' garbage collection
Close #1
rst.Close
Set rst = Nothing
rst2.Close
Set rst2 = Nothing
End Sub
I admit that what you're trying to do here is already less than ideal. I don't often work with data where this many fields are needed.
The solution here is basically to manage two different recordset objects.
Public Sub ImportTextFile()
' to use the ADODB.Recordset, be sure you have a reference set to ADO
Dim rst As ADODb.Recordset
Dim rst2 As ADODb.Recordset
Dim strFile As String
Dim strInput As String
Dim varSplit As Variant
Dim intCount As Integer
Set rst = New ADODb.Recordset
Set rst2 = New ADODb.Recordset
' CHANGE THE TABLE NAME HERE
rst.Open "Importtabledata", CurrentProject.Connection, adOpenDynamic, adLockOptimistic
rst2.Open "importtabledata2", CurrentProject.Connection, adOpenDynamic, adLockOptimistic
' CHANGE THE TEXT FILE NAME AND LOCATION HERE
strFile = "G:\Home\RiskMgtReports\AutoDatabase\fullextract.txt"
Open strFile For Input As #1
Dim i as Integer
Do Until EOF(1)
' This counter is just to get to the applicable line before importing
intCount = intCount + 1
' reads the text file line by line
Line Input #1, strInput
' starts importing on the second line. Change the number to match which line you
' want to start importing from
If intCount >= 256 Then
' creates a single dimension array using the split function
varSplit = Split(strInput, vbTab, , vbBinaryCompare)
' adds the record
With rst
.AddNew
For i = 1 to 255
.Fields(i) = varSplit(i-1)
Next i
.Update
'.MoveNext 'I don't think you should need this
End With
With rst2
.AddNew
For i = 256 to UBound(varSplit)
.Fields(i) = varSplit(i-1)
Next i
.Update
End With
End If
Loop
' garbage collection
Close #1
rst.Close
Set rst = Nothing
rst2.Close
Set rst2 = Nothing
End Sub
In a windows application I have a query that im trying to insert the current date on my mysql database
query below:
SqlVentaCasas1 = "INSERT INTO VentaCasasHistory (ID, Direccion, Estatus, Precio, " & _
"NumeroDias, FechaHoy, Agente, Compania, Unidad, Ciudad ) VALUES ('" & _
AddIDCasas2 & "','" & AddDireccionCasas2 & "','" & AddEstatusCasas2 & "'," & AddPrecioCasas2 & ", 0, CURDATE(), '" & AgenteNameCasas2 & "','" & AgenteCompaniaCasas2 & "', '" & AddUnidadCasas2 & "', '" & AddCiudadCasas2 & "' );"
CommandVentaCasas1 = New MySqlCommand(SqlVentaCasas1, con)
CommandVentaCasas1.CommandType = CommandType.Text
CommandVentaCasas1.ExecuteNonQuery()
when i input the values that i want to insert into mysql everything runs smoothly except that when i check the database for the date entered i find myself with the 0000-00-00
on the other hand, when i run the same query from PHPmyAdmin
INSERT INTO `VentaCasasHistory`(`ID`, `Direccion`, `Estatus`, `Precio`, `NumeroDias`, `FechaHoy`, `Agente`, `Compania`, `Unidad`, `Ciudad`) VALUES ([String1],[String2],[String3],[Integer1],[Integer2],CURDATE(),[String4],[String5],[String6],[String7])
where FechaHoy is CURDATE() is does insert correctly the date that should be.
I cant seem to find what is the problem, As i understand it will only insert 0000-00-00 if there is something wrong with the date when been entered.
the reason i kept both queries "identical" was to understand what im doing wrong and I know that they can be subject to SQL injection.
your help would be very appreciated.
Leo P.
this is the code i have for the last piece that you told me.
Dim StringDate As String
StringDate = Date.Today.ToString("yyyy-MM-dd")
SqlVentaCasas1 = "INSERT INTO VentaCasasHistory (ID, Direccion, Estatus, Precio, " & _
"NumeroDias, FechaHoy, Agente, Compania, Unidad, Ciudad ) VALUES ('" & _
AddIDCasas2 & "','" & AddDireccionCasas2 & "','" & AddEstatusCasas2 & "'," & AddPrecioCasas2 & ", 0, STR_TO_DATE('" & StringDate & "', GET_FORMAT(DATE,'ISO')), '" & AgenteNameCasas2 & "','" & AgenteCompaniaCasas2 & "', '" & AddUnidadCasas2 & "', '" & AddCiudadCasas2 & "' );"
unfortunately it does not work and i still get the 0000-00-00.
CURDATE() should really be specified as default value used in CREATE TABLE. In other words, you don't need to put it in as part of a query as when you insert a new record the field with default value set to CURDATE() will have the date automatically inserted.
F.ex:
CREATE TABLE MyTable
(
ID int NOT NULL,
MyName varchar(30) NOT NULL,
MyDate datetime NOT NULL DEFAULT CURDATE(),
PRIMARY KEY (ID)
)
INSERT INTO MyTable (MyName) VALUES ('Epistemex')
Will set the MyDate field to CURDATE().
Hope this helps.
i have a very simple report that is generated from just one table. one of the columns in the table is a date.
i need to be able to allow the user of the report to enter a range of dates and display data only between those dates.
how do i do this>?
I don't like hardwiring either parameters or form references in the recordsources of forms/reports, so I would amend #Remou's idea to instead set the RecordSource in the OnOpen event of the report. That is, first open the form, collect the values of the selected dates, and then plug those into the where clause of the report's RecordSource. Something like this (copied from a real report of mine):
Dim strRecordSource As String
DoCmd.OpenForm "dlgDateRange", , , , , acDialog, "ThisYear"
If IsLoaded("dlgDateRange") Then
With Forms!dlgDateRange
If .Tag = "Cancel" Then
Cancel = True
Else
Me.Filter = "[InvoiceDate] Between #" & !txtStart & "# AND #" & !txtEnd & "#"
Me.FilterOn = True
Me!lblDateRange.Caption = StrConv(Trim(("from " + varZLStoNull(Format(!txtStart, "mm/dd/yyyy"))) & (" to " + varZLStoNull(Format(!txtEnd, "mm/dd/yyyy")))), vbProperCase)
End If
End With
DoCmd.Close acForm, "dlgDateRange"
End If
Some comments:
The dialog form called here is much more complex than what you need, as it has a bunch of predefined date ranges, set based on the dialog form's OpenArgs parameter. The form looks like this:
(source: dfenton.com)
I use Stephan Lebans date picker code for allowing the user to pick a date from a calendar control.
The code for setting the date ranges is this, and all I have to do is pass it one of the cases of this CASE SELECT:
Public Sub SetDates(strType As String, ctlStart As Control, ctlEnd As Control)
Dim dteStart As Date
Dim dteEnd As Date
Dim ctl As Control
Select Case strType
Case "EndOnly" ' OK
dteStart = #1/1/1980#
ctlStart.Enabled = False
dteEnd = Date
Case "Trace" ' OK
dteStart = DateAdd("d", -7, Date)
dteEnd = DateAdd("d", 7, Date)
Case "LastWeek" ' OK
dteStart = Date - Weekday(Date, vbMonday) - 6
dteEnd = dteStart + 6
Case "ThisWeek" ' OK
dteStart = Date - Weekday(Date, vbMonday) + 1
dteEnd = dteStart + 6
Case "LastMonth" ' OK
dteStart = month(DateAdd("m", -1, Date)) & "/01/" & year(DateAdd("m", -1, Date))
dteEnd = DateAdd("m", 1, dteStart) - 1
Case "ThisMonth" ' OK
dteStart = month(Date) & "/01/" & year(Date)
dteEnd = DateAdd("m", 1, dteStart) - 1
Case "LastQuarter" ' OK
dteStart = DateSerial(year(DateAdd("q", -1, Date)), (3 * Format(DateAdd("q", -1, Date), "q")) - 2, 1)
dteEnd = DateAdd("q", 1, dteStart) - 1
Case "ThisQuarter" ' OK
dteStart = DateSerial(year(Date), (3 * Format(Date, "q")) - 2, 1)
dteEnd = DateAdd("q", 1, dteStart) - 1
Case "LastYear" ' OK
dteStart = "01/01/" & year(Date) - 1
dteEnd = "12/31/" & year(Date) - 1
Case "ThisYear" ' OK
dteStart = "01/01/" & year(Date)
dteEnd = "12/31/" & year(Date)
Case "LastFY" ' OK
dteStart = "09/01/" & year(DateAdd("m", 4, Date)) - 2
dteEnd = DateAdd("yyyy", 1, dteStart) - 1
Case "ThisFY" ' OK
dteStart = "09/01/" & year(DateAdd("m", 4, Date)) - 1
dteEnd = DateAdd("yyyy", 1, dteStart) - 1
Case "Last3Years" ' OK
dteStart = "01/01/" & year(Date) - 2
dteEnd = Date
Case "BeforeLast3Years" ' OK
dteEnd = DateValue("01/01/" & year(Date) - 2) - 1
Case Else
dteStart = Date
dteEnd = Date
End Select
If ctlStart.Enabled Then
If dteStart = 0 Then
ctlStart = Null
Else
ctlStart = Format(dteStart, "mm/dd/yyyy")
End If
End If
If ctlEnd.Enabled Then
If dteEnd = 0 Then
ctlEnd = Null
Else
ctlEnd = Format(dteEnd, "mm/dd/yyyy")
End If
End If
For Each ctl In ctlStart.Parent!optPresetDates.Controls
If ctl.ControlType <> acLabel Then
If Replace(ctl.Controls(0).Caption, " ", vbNullString) = strType Then
ctlStart.Parent!optPresetDates = ctl.OptionValue
Exit For
End If
End If
Next ctl
Set ctl = Nothing
End Sub
That's way more information than you need, really, but the point I'm trying to make is that you should consider tying your report's recordsource to parameters or a dialog form.
The best solution is probably to create a small form that allows the user to enter dates. The query that the report is based on can then refer to the form:
SELECT f1,f2,f3 FROM Table
WHERE SomeDate
BETWEEN Forms!DateSelect!StartDate AND Forms!DateSelect!EndDate
What I would do is create a query that selects all of the rows in the table and for the date field I'd set up a couple of parameters. Try the following:
Specify the date field like so in the query design:
Format([YourDateField],"mmm. dd, yyyy")
And for the criteria write:
Between Format([From],"mmm. yy, dddd") And Format([To],"mmm. dd. yyyy")
When you run the query, two input boxes should come up asking for the From and To dates in the specified format.