vba - VB/VBA If..ElseIf..Then,其中每个 ElseIf..Then 位于一行

标签 vba vb6

我想使用 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 代码生成公式不必在公式中使用换行符?

最佳答案

选择案例而不是If...ElseIf...End If

enter image description here

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

关于vba - VB/VBA If..ElseIf..Then,其中每个 ElseIf..Then 位于一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76839611/

相关文章:

crystal-reports - 在运行时将 Crystal Reports ParameterField 设置为 NULL

vba - 以并排模式查找窗口

vba - 从 Excel VBA 更新 SQL Server 表

vba - 使用部分变量名称检索最后修改的文件

java - 如何制作一个自动同步的程序

vb6 - Windows 2012 Server 上的 VB 6 数据访问组件安装

vba - 激活工作表 1,否则激活另一个工作表

excel - 需要代码根据值删除行(VBA)

vba - 如何判断我的代码在哪个模块中执行?

post - VB6 POST 到具有内容类型表单数据的服务器未收到参数