Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Funzione Replace da VBA

594 views
Skip to first unread message

mic...@inwind.it

unread,
May 2, 2012, 5:34:56 AM5/2/12
to
Salve,
da un po' di tempo mi è venuta la fissa di non utilizzare più nei miei
DB le query 'normali' bensì quelle via codice (DoCmd.RunSQL).
Questo il mio quesito:
Importando un file .txt, per poi accodarlo via codice ad una tabella
esiste (DoCmd.RunSQL "INSERT INTO etc.),
mi capita, a causa della presenza di un apostrofo, di mandare in
errore il codice.
Il problema in effetti, l'ho risolto lanciando preventivamente una
query di aggiornamento (DoCmd.OpenQuery etc,) nella quale ho impostato
il campo
[Aggiorna a] con l'istruzione Replace([Valore1];"'";" ").
La mia curiosità è quella di 'tradurre' tale query di comando in un
codice VBA.
Questa l'SQL della query di agiornamento - UPDATE Tabella1 SET
Tabella1.Valore1 = Replace([Valore1],"'"," ");
Purtroppo comè noto l'istruzone DoCmd.RunSQL mal digerisce la presenza
di apici all'interno dell'istruzione.
Ringrazio in anticipo a chi mi fornirà la giusta dritta.
Ciao
Michele

Fair87

unread,
May 2, 2012, 6:31:40 AM5/2/12
to
Alcune cose: privilegia l'uso di database.Execute invece di RunSQL
per quanto riguarda l'apostrofo è un comportamento noto di tutti i linguaggi e non si risolve con lo spazioni(" ") ma con il doppio apostrofo ("''")
Puoi usare replace o una funzione tua (se devi fare altre sostituzioni)
Per ultimo, io non utilizzerei le funzioni direttamente nell'SQL (x questioni di portabilità)

Bruno Campanini

unread,
May 2, 2012, 10:21:15 AM5/2/12
to
mic...@inwind.it expressed precisely :
Copiati questa funzione in un modulo:
============================================
Public Function FSR(SR As Variant) As Variant
'
' Formattazione Stringa di Ricerca.
' Bruno Campanini - 06-04-2005
'
'
' SR può essere Data, Stringa, Numero
' Se SR è Stringa può contenere qualunque carattere,
' inclusi Chr(34) = " e Chr(39) = '
'
' La sintassi sarà sempre ed unicamente:
' (Where) "[TableField]='" & FSR(SR) & "'"
'
' Occorre tener presente che SR potrà essere scritta
' nella sua forma normale se collocata in un campo di Form.
' Ad esempio: Trattoria "L'Isola del Tesoro" con alloggio
'
' Qualora venga passata via codice la medesima dovrà essere
' formattata raddoppiando le eventuali virgolette Chr(34) = "
' contenute nel suo interno, indi racchiusa per intero
' entro DUE virgolette. Nel rispetto della convenzione VB.
' Così sarà: "Trattoria ""L'Isola del Tesoro"" con alloggio"
'
SR = Replace(SR, Chr(34), """ & Chr(34) & """)
SR = Replace(SR, Chr(39), """ & Chr(39) & """)

If IsDate(SR) Then
SR = Chr(35) & Format(SR, "mm-dd-yy") & Chr(35)
ElseIf IsNumeric(SR) Then
Else
SR = Chr(34) & SR & Chr(34)
End If

FSR = SR

End Function
===============================================

Ed usala poi così:

UPDATE Tabella1 SET
Tabella1.Valore1 = " FSR([Valore1]) & ";"

Però usare nel nome di una variabile o di un campo caratteri diversi
dai 36 alfanumerici è proprio una cosa che grida vendetta!!!

Bruno


tommaso

unread,
May 2, 2012, 3:35:29 PM5/2/12
to
Il giorno mercoledì 2 maggio 2012 11:34:56 UTC+2, mic...@inwind.it ha scritto:

Io uso questo (trovato sul web, come si può vedere dal codice, riportato tale e quale)


In un modulo:

'*********** Code Start ***********
Public Function Replace( _
Expression As String, _
Find As String, _
ReplaceWith As String, _
Optional Start As Integer = 1, _
Optional Count As Integer = -1, _
Optional Compare As Integer = vbBinaryCompare _
)

'*******************************************
'Name: Replace (Function)
'Purpose: Access97 version of the A2k Replace function
'Author: Terry Kreft
'Date: June 01, 2000, 02:44:34
'Called by: Any
'Calls: None
'Inputs: Expression - String to Search
' Find - Sub-String to be replaced
' ReplaceWith - Sub-String to insert
' Start - Optional start of string to return and replace
' Count - Optional number of replacements to carry out
' Compare - Optional compare method to use _
(valid values are 0, 1, 2)
'Output: 1) If Expression is zero-length then a zero-length string ("")
' 2) If Expression is Null then an error
' 2) If Find is zero-length then a copy of Expression.
' 3) If ReplaceWith is zero-length then a copy of _
Expression with all occurences of find removed.
' 4) If Start > Len(Expression) then a zero-length string.
' 5) If Count is 0 then a copy of Expression.
'*******************************************

Dim intInstr As Integer
Dim intCount As Integer
Dim intFindLen As Integer
Dim intRepLen As Integer
Dim strRet As String
Dim strTemp As String
On Error GoTo Replace_err

intFindLen = Len(Find)
intRepLen = Len(ReplaceWith)

If Compare < vbBinaryCompare Or Compare > vbDatabaseCompare Then
Err.Raise 1 + vbObjectError, Description:="Bad compare method"
ElseIf Len(Expression) = 0 Or Start > Len(Expression) Then
strRet = ""
ElseIf Count = 0 Or intFindLen = 0 Then
strRet = Expression
Else
strTemp = Mid(Expression, Start)
intCount = Count
intInstr = InStr(1, strTemp, Find, Compare)
Do While intInstr > 0
strRet = strRet & Left(strTemp, intInstr - 1) & ReplaceWith
strTemp = Mid(strTemp, intInstr + Len(Find))
intInstr = InStr(1, strTemp, Find, Compare)
intCount = intCount - 1
If intCount = 0 Then Exit Do
Loop
End If
strRet = strRet & strTemp
Replace_end:
Replace = strRet
Exit Function
Replace_err:
strRet = ""
With Err
.Raise .Number, .Source, .Description, .HelpFile, .HelpContext
End With
End Function
'*********** Code End ***********

in una Query:
UPDATE nometabella SET nomecampo = REPLACE(nomecampo, " ", "")

può essere utilizzato oltre da query, da Vba...Esempio:

Dim strSql As String
strSql = "UPDATE MiaTabella SET MioCampo = REPLACE(MioCampo, "" "", """");" 'Toglie gli spazi dal campo
DoCmd.RunSQL strSql

Spero di essere stato utile
Ciao
Tommaso

0 new messages