2017-01-05 2 views
3

Я пишу макрос, который должен запускать запросы для передачи данных из excel в базу данных Access, и все работает нормально, однако, если я хочу использовать String в одном из этих запросов, Я печатать их, как это:Простой способ использования объявленных строк в запросе в VBA

'" & Lijn & "' 

Я знаю, что следующий код (который написан на VBA) является способ проще писать Javascript, используя вопросительные знаки и SetString:

VBA:

Dim ShiftsQ As String 
ShiftsQ = "INSERT INTO Shifts(Lijn, Operator, Ploeg, Teamleider) VALUES ('" & Lijn & "', '" & Operator & "', '" & Ploeg & "', '" & Teamleider & "');" 

Javascript:

var ShiftsQ = SQL.prepareStatement(INSERT INTO Shifts(Lijn, Operator, Ploeg, Teamleider) VALUES (?, ?, ?, ?); 
ShiftsQ.setString(1, Lijn); 
ShiftsQ.setString(2, Operator); 
ShiftsQ.setString(3, Ploeg); 
ShiftsQ.setString(4, Teamleider); 

Есть в любом случае, чтобы написать код VBA, как в Javascript один?

ответ

2

насколько я знаю, нет ничего подобного .NET string.Format() метод VBA. Но вы можете написать свою собственную версию такой функции, которая использует depys и возвращает форматированную строку.

Private Sub Main() 
    ' Your actual query 
    ' The deputys are indexed in curley brackets (inspired from the .NET syntax of the equivalent function, making your code easy to read for .NET programmers) 
    Dim qry As String 
    qry = "SELECT {0}, {1} FROM {2} WHERE {3}" 

    ' The values to set for the deputys in your query 
    Dim parameters(3) As String 
    parameters(0) = "firstname" 
    parameters(1) = "lastname" 
    parameters(2) = "users" 
    parameters(3) = "userID = 'M463'" 

    ' For demo purposes, this will display the query in a message box 
    ' Instead of the MsgBox, you would use the formatted query to execute against the database 
    MsgBox FormatString(qry, parameters) 
End Sub 

' This is where the magic happens, the deputys in the given string will be replaced with the actual values from the provided array 
Private Function FormatString(strInput As String, paramValues() As String) 
    ' This will be our return value 
    Dim strOutput As String 
    strOutput = strInput 

    ' Verify that the given count of parameters matches the given count of deputys in the input string 
    Dim maxParamIndex As Integer 
    maxParamIndex = UBound(paramValues) 

    Dim deputyCount As Integer 

    For i = 1 To Len(strOutput) + 1 Step 1 
     If Mid(strOutput, i, 3) = "{" & deputyCount & "}" Then 
      deputyCount = deputyCount + 1 
     End If 
    Next 

    ' If there is a mismatch between the count of parameters and the count of deputys, display exception message and exit the function 
    ' Adding +1 to maxParamIndex is neccessary, as maxParamIndex refers to the maximum index (starting at 0, not 1) of the given array and deputyCount refers to the actual count of deputys (starting at 1) 
    If maxParamIndex + 1 <> deputyCount Then 
     MsgBox "Number of deputys has to match number of parameters for the given string:" & vbCrLf & strInput, vbCritical, "Exception in Function FormatString" 
     FormatString = "" 
    End If 

    ' Iterate through the array and replace the deputys with the given values 
    For i = 0 To maxParamIndex Step 1 
     strOutput = Replace(strOutput, "{" & i & "}", paramValues(i)) 
    Next 

    ' return the formatted string 
    FormatString = strOutput 
End Function 

Результат примера:

enter image description here

+0

Ничего себе, спасибо, это даже лучше, чем ответ, предоставленный A.S.H. так как это делает код еще более понятным. Благодаря! – Rick

+1

Добро пожаловать. :-) Обратите внимание, что, по соображениям безопасности, вы, вероятно, не должны показывать окно с ошибкой с текстом запроса пользователю. Но это делает отладку намного проще, и когда ваш код верен, MsgBox не должен появляться вообще, так что это вряд ли будет проблемой в реальной ситуации. – M463

+0

Хорошо, спасибо, что сообщили мне. я получил еще одну проблему с кодом: когда я запускаю его, я получаю следующее сообщение об ошибке: Не удается найти проект или библиотеку И это что-то делать с этим кусок кода: Dim ParamCount As Integer maxParamIndex = UBound (paramValues) – Rick

1

Если я сталкиваюсь с этой проблемой, я бы просто решить эту проблему в одиночку (Althoug там может быть другим «стандартным» решение), определив свою собственную простую, глобальную функцию (поставить в любом стандартном модуле кода)

Public Function S_(str as String) as String 
    S_ = chr(39) & str & chr(39) 
End Function 

ShiftsQ = "INSERT INTO Shifts(Lijn, Operator, Ploeg, Teamleider) VALUES (" & S_(Lijn) & ", " & S_(Operator) & ", " & S_(Ploeg) & ", " & S_(Teamleider) & ");" 

Таким образом, я буду следовать простое и систематическому правилу во всем моем проекте, который называют S_(param) по любому параметру текстового типа в моих запросах ...

+0

Спасибо, я обязательно попробовать это! – Rick

Смежные вопросы