5如果声明公式

时间:2017-07-06 19:48:03

标签: excel vba excel-vba excel-formula

我最近创建了一个IF公式,只在2个语句中运行宏,但我需要再添加3个语句。

这是为了改变文件名。所以我使用LEN来确定它是什么类型的文件,然后运行适当的公式来修剪我不想要的内容。

示例:

173d0221.pdf = S-173-D022 Description.pdf  =CHAR(83)&CHAR(45)&LEFT(B11,LEN(B11)-9)&CHAR(45)&UPPER(MID(B11,4,LEN(B11)-8))&CHAR(32)&D11&E11

173d02210.pdf = S-173-D022 Description.pdf =CHAR(83)&CHAR(45)&LEFT(B12,LEN(B12)-10)&CHAR(45)&UPPER(MID(B12,4,LEN(B12)-9))&CHAR(32)&D12&E12

173d170c141.pdf = SD-170-C14 Description.pdf  =CHAR(83)&CHAR(68)&CHAR(45)&UPPER(MID(B13,5,LEN(B13)-12))&CHAR(45)&UPPER(MID(B13,8,LEN(B13)-12)&CHAR(32)&D13&E13)

REF-173d0221.pdf = REF-173-D022 Description.pdf  =LEFT(B14,LEN(B14)-9)&CHAR(45)&UPPER(MID(B14,8,LEN(B14)-12))&CHAR(32)&D14&E14

REF-173d02210.pdf = REF-173-D022 Description.pdf  =LEFT(B15,LEN(B15)-10)&CHAR(45)&UPPER(MID(B15,8,LEN(B15)-13))&CHAR(32)&D15&E15

我无法将它们连接在一起,以便根据单元格的长度应用正确的公式。

注意:我使用的是CHAR(83)&CHAR(45)而不是"S-",因为VBA并不喜欢这个文字。一旦一切顺利,我将用"B12"更新" & aCell & "单元格标记。

我的vba代码如下:

.Range("C2:C" & LastRow).Formula = "=IF(LEN(" & aCell & ")=12,CHAR(83)&CHAR(45)&LEFT(" & aCell & ",LEN(" & aCell & ")-9)&CHAR(45)&UPPER(MID(" & aCell & ",4,LEN(" & aCell & ")-8))&CHAR(32)&" & dCell & "&" & eCell & ",LEFT(" & aCell & ",LEN(" & aCell & ")-9)&CHAR(45)&UPPER(MID(" & aCell & ",8,LEN(" & aCell & ")-12))&CHAR(32)&" & dCell & "&" & eCell & ")"

1 个答案:

答案 0 :(得分:3)

这似乎适用于前三个示例公式。

enter image description here

我会留给你将剩余的2个公式翻译成VBA,你可以按照我的例子做到这一点:)

Option Explicit

Sub foo()
Dim rng As Range, aCell As Range
Dim val As String
Set rng = Range("B1:B5")  '## Modify the input range as needed.
For Each aCell In rng.Cells
    Select Case Len(aCell)
        Case 12
            val = "S-" & Left(aCell, Len(aCell) - 9) & "-" & Mid(aCell, 4, Len(aCell) - 8)
        Case 13
            val = "S-" & Left(aCell, Len(aCell) - 10) & "-" & Mid(aCell, 4, Len(aCell) - 9)
        Case 15
            val = "SD-" & Mid(aCell, 5, Len(aCell) - 12) & "-" & Mid(aCell, 8, Len(aCell) - 12)
        Case 16
            val = "REF-" '## Modify as needed
        Case 17
            val = "REF-" '## Modify as needed
        Case Else
            'maybe warn the user this input is not anticipated...
            MsgBox "Unsupported length!", vbInformation
    End Select
    val = UCase(val)
    '## Append the values from column D,E:
    val = val & " " & aCell.Offset(, 2) & aCell.Offset(, 3)
    '## Write out to the workbook in column F, modify the "5" to specify a different location if needed e.g., "-1" would put it in column A, "0" would put in same column B, etc.
    aCell.Offset(, 4).Value = val
Next
End Sub