创建一个包含变量的字符串,但变量周围不带引号

问题描述 投票:0回答:1

我已经浏览了这里的一些示例,但似乎没有什么完全符合我的需要。 我需要采用变量.....DeptVar =“E22E27E33”(这是用户表单的结果) 并把它变成这个 [Department] = "E22" 等等。 我遇到的问题是在部门 (E22) 周围加上引号

这是我的代码。我已经尝试了我能想到的所有变体来添加引号。

Sub CreateString ()
Dim Index as Integer
Dim DeptVar as String
Dim DeptString as String

DeptVar = "E22E27E33" ' <---This is how it is gathered from the userform
Index = 1

Do While Index < 8
    If DeptString = "" Then
     DeptString = "[Department] = " & "" Mid(DeptVar, index, 3) & ""
Else: DeptString = DeptString & "," " AND [Department = " & Mid, index, 3)

end if

index = index +3

loop

end Sub

它当前返回: [部门] = E22,并且 [部门] = E27,并且 [部门] = E33

我需要它来返回这个: [部门] = “E22”,并且 [部门] = “E27”,并且 [部门] = “E33”

excel vba
1个回答
0
投票
Sub CreateString()

    Const TMPL = "[Department] = ""###"""
    Dim DeptVar As String, DeptString As String, i As Long, s As String
    
    DeptVar = "E22E27E33" ' <---This is how it is gathered from the userform
    
    i = 1
    Do While i < Len(DeptVar)
        DeptString = DeptString & s & Replace(TMPL, "###", Mid(DeptVar, i, 3))
        i = i + 3
        s = ", AND "
    Loop
    Debug.Print DeptString
  
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.