Excel VBA - 从文本文件导入 SQL 语句时使用替换

Excel VBA - Use of Replace when Importing SQL Statements from a text file

起初我可能会防止我在用英语写作时可能会犯一些错误,因为它不是我的母语。

我正在使用 Excel VBA 和 SQL 学习一些东西,让我的工作更轻松。每个季度,我必须制作一份包含大约 60 个表格的报告。所以我正在编写一个程序来帮助我从 Access 数据库中获取一些数据,将其导入新的 Excel 工作文件并以更好的方式对其进行格式化以便发布。 为此,我使用 ADO 连接,然后在主 excel 文件中为每个 Table 创建一个 spreadsheet,并用一个记录集填充 sheet。

为了使调试更容易,我选择将每个 SQL 语句放在一个文本文件中。我构建了一个函数来读取该文件的内容。我还使用了用户在启动我的 VBA 程序。 为此,我在读取文本文件并将其导入字符串变量后使用了 REPLACE。

我的问题是,对于某些文件,它进行了替换并且一切正常(创建了一个新文件并包含我的 Recordset),但是对于我的一些文本文件,REPLACE 没有替换我的关键字。

这是我的一段代码,只有我认为需要清理的部分。不能 post 全部,因为它包含一些集合和 class 个模块:

    ''' Version du programme ou on crée tous les fichiers dans form_2 et où on les exporte après/ version of my program where I create all Tables im my main file containing the code, export them in a new workbook and delete them

'Déclaration initiale/ Init of variables

Dim strMyPath As String, strDBName As String, strDB As String
Dim rs As New ADODB.Recordset
Dim db2 As New ADODB.Connection

'Appel de xx pour remplir anmois/ calling fct_anmois to fill my where conditions with the 5 couples years-quarter

Call fct_anmois(InputBox("Entre une valeur année", "Année"), InputBox("Entre une valeur codée mois: 21- 1er Trimestre; 22- 2ème Trimestre; 23- 3ème Trimestre; 24- 4ème Trimestre"))


'Quatres premiers Tableaux/ 4 1st Tables

' A entrer avec des parametres input utilisateurs que je définirai après: voir ma collection AnTrimes/ 

Dim STR1 As String

STR1 = "((Base1.Annee)=" & anmois.item(5).Ann & " ) And ((Base1.Mois)=" & Chr$(34) & anmois.item(5).Trime & Chr$(34) & ")"

Dim STR2 As String
STR2 = "((Base1.Annee)=" & anmois.item(1).Ann & " and (Base1.Mois)=" & Chr$(34) & anmois.item(1).Trime & Chr$(34) & ") or " & _
       "((Base1.Annee)=" & anmois.item(2).Ann & " and (Base1.Mois)=" & Chr$(34) & anmois.item(2).Trime & Chr$(34) & ") or " & _
       "((Base1.Annee)=" & anmois.item(3).Ann & " and (Base1.Mois)=" & Chr$(34) & anmois.item(3).Trime & Chr$(34) & ") or " & _
       "((Base1.Annee)=" & anmois.item(4).Ann & " and (Base1.Mois)=" & Chr$(34) & anmois.item(4).Trime & Chr$(34) & ") or " & _
       "((Base1.Annee)=" & anmois.item(5).Ann & " and (Base1.Mois)=" & Chr$(34) & anmois.item(5).Trime & Chr$(34) & ")"


'Debug.Print (STR1)
'Debug.Print (STR2)

'--------------
'L'Objet CONNEXION/ Connexion Object

''''''''''''''''Définition du Chemin d'accès vers la base de données/ Database workpath

strDBName = "Bulletin_Light.accdb"
strMyPath = ThisWorkbook.Path
strDB = strMyPath & "\" & strDBName

''''''''''''''''Connect to a data source:
db2.Open ConnectionString:="Provider = Microsoft.ACE.OLEDB.12.0; data source=" & strDB

'''''''''''''''Chargement du vecteur syntaxe sql par appel de la procédure bosql/ Fill two vector, one containing text file name vartitres(), the other the content of the text file in which I have my SQL statement with a STR1/ STR2 in place of my WHERE Condition bouclesql(). It does it for each text file in a defined folder

Call bosql

Dim i As Integer
i = 0

''''''''''''''''Début de la boucle géante Par Feuille

For i = 0 To UBound(bouclesql)

    'Création de la nouvelle feuille/ Create a new worksheet names it like the text file ,checks if it already exists and deletes ii in case

Dim sht As Worksheet, shtname As String
    Set sht = ThisWorkbook.Sheets.add(after:=Worksheets(Worksheets.count)) 'worksheets(ThisWorkbook.Sheets.count)
    If sht.name = Replace(vartitres(i), ".txt", "") _
        Then ThisWorkbook.Worksheets(sht.name).Delete _
        Else sht.name = Replace(vartitres(i), ".txt", "")

    sht.Cells.Font.name = "Times New Roman"
    sht.Cells.Font.Size = 10


''' Correction du STR1/STR2 (s'il y en a) de la syntaxe SQL i/ Correction of the keyword STR1/STR2 in the WHERE Clause of my bouclesql() by the right content stored in these variables
'''Store the right statement in STRALL

''' de bouclesql(i)par la bonne condition sur le WHERE


Dim STRALL As String
If (vartitres(i) = "Tab1.txt" Or vartitres(i) = "Tab2.txt" Or vartitres    (i) = "Tab3.txt" Or vartitres(i) = "Tab4.txt") Then 
    STRALL = Replace(bouclesql(i), "STR1", STR1) 
Else 
    STRALL = Replace(bouclesql(i), "STR2", STR2)
End If

    'Debug.Print bouclesql(i)
    Debug.Print STRALL

'SQL Statement
    Dim cmd As New ADODB.Command
        cmd.CommandType = adCmdText
        cmd.CommandText = STRALL
        cmd.ActiveConnection = db2


'''Ouverture du recordset

rs.Open cmd, , adOpenKeyset, adLockOptimistic

可能是区分大小写的问题? 你的代码

[...] Replace(bouclesql(i), "STR1", STR1) [...]
[...] Replace(bouclesql(i), "STR2", STR2) [...]

大写"STR1"或"STR2"可能有问题。 例如:

    Dim strTry1 As String = "dog_cat_duck"
    Dim strTry2 As String = "Dog_Cat_Duck"

    MsgBox(Replace(strTry1, "dog", "car"))
    MsgBox(Replace(strTry2, "dog", "car"))

替换 strTry1 有效。 替换 strTry2 不起作用。

在使用 Replace() 之前尝试使用 lCase / uCase

编辑/提示: 这读起来很糟糕:

Dim STRALL As String
If (vartitres(i) = "Tab1.txt" Or vartitres(i) = "Tab2.txt" Or vartitres(i) = "Tab3.txt" Or vartitres(i) = "Tab4.txt") _
Then STRALL = Replace(bouclesql(i), "STR1", STR1) Else STRALL = Replace(bouclesql(i), "STR2", STR2)

好多了:

Dim STRALL As String
If (vartitres(i) = "Tab1.txt" Or vartitres(i) = "Tab2.txt" Or vartitres(i) = "Tab3.txt" Or vartitres(i) = "Tab4.txt") Then 
    STRALL = Replace(bouclesql(i), "STR1", STR1) 
Else 
    STRALL = Replace(bouclesql(i), "STR2", STR2)
End If