我想使用 Excel 和字符串连接来生成一些映射的 VB 代码(值 A 和值 B => 值 C)。实际上,我将把生成的 VB 代码插入到使用 VB 语法的 Crystal Reports 自定义函数中的函数中。
在 Excel 中,我有三列包含映射值:前两列具有映射/函数的输入值,而第三列具有输出值。我用一堆值填充了这些列(想象所有 xxx、yyy 和 zzz 都是唯一值)。
第四列是一个字符串连接公式,它实现了一个巨大的 VB If..ElseIf..ElseIf..ElseIf..EndIf 雕像中的映射。每行必须生成一个 ElseIf..Then VB 语句。我需要将生成的代码如下所示(我将手动键入
If
行和 EndIf
行。)
' This first line just lets all other lines be an "ElseIf" statement, making the Excel formula that renders this code the same for every entry.
If False Then foo = ""
ElseIf strProductCode = "xxx" And strPackageLength = "yyy" Then foo = "zzz"
ElseIf strProductCode = "xxx" And strPackageLength = "yyy" Then foo = "zzz"
ElseIf strProductCode = "xxx" And strPackageLength = "yyy" Then foo = "zzz"
ElseIf strProductCode = "xxx" And strPackageLength = "yyy" Then foo = "zzz"
EndIf
生成代码的公式示例如下:
="ElseIf strProductCode = """ & A1 & """ And strPackageLength = """ & B1 & """ then foo = """ & C1 & """"
该公式忠实地生成了 VB。然而,上面的 VB 会产生语法错误:
“编译错误。没有 If 的 Else”
是的,我知道
Then
部分通常位于新行上,但是是否有某种语法允许将代码格式化为上述格式,以便我的 Excel 代码生成公式不必在公式中求助于换行符?
Select Case
而不是If...ElseIf...End If
Excel公式
=REPT(" ",8)&"Case strProductCode = """&A1&""" And strPackageLength = """&B1&""": foo = """&C1&""""
VBA代码
Sub Test()
Dim strProductCode As String: strProductCode = "A2"
Dim strPackageLength As String: strPackageLength = "20"
Dim foo As String
Select Case True
Case strProductCode = "A1" And strPackageLength = "10": foo = "C1"
Case strProductCode = "A2" And strPackageLength = "20": foo = "C2"
Case strProductCode = "A3" And strPackageLength = "30": foo = "C3"
Case strProductCode = "A4" And strPackageLength = "40": foo = "C4"
Case Else: foo = ""
End Select
MsgBox """foo"" is equal to """ & foo & """.", vbInformation
End Sub