将包含Loop的公式(如果or和else)转换为VBA代码

时间:2019-03-16 19:27:20

标签: excel vba excel-formula

两个公式给我带来了很多麻烦。我曾经将公式手动插入第一行第一列,然后将其复制并粘贴到所有列中。这是两个公式 对于

Column A: =(IF(C2="","",IF(LEFT(C2,3)="Bus","BU CRM","CSI ACE")))

Column B:  =IF(C2="","",IF(LEFT(C2,3)="CSI", "",RIGHT(C2,LEN(C2)-14)))

这是我的尝试

A列:

`FinalRow = Cells(Rows.Count, 1).End(xlUp).Row
For m = 1 To FinalRow
If Cells.Left(m, 3) = Bus Then Cells(m, 1) = "BU CRM" Else Cells(m, 1) = "CSI ACE"
Next m
End If`

B列:

FinalRow = Cells(Rows.Count, 1).End(xlUp).Row

For J = 1 To FinalRow

If Cells(J, 3) = "" Or Cells.Left(J, 3) = "CSI" _
Then Cells(J, 2) = "" _
Else Cells(J, 2) = Right.(Cells(J, 3) - 14) _

Next J

End If

基本上,我为A列查看C列的代码,如果C列中的前三个字母是“ Bus”,则A列应为“ BU CRM”,否则应为“ CSI ACE”

因此,B列应查看C列,并且如果C列中的单元格以“ CSI”开头,则应在B列“”中返回。如果C列不是以“ CS”开头,则将最后14个字母/数字返回到B列。

我希望我已经阐明了我的问题和疑问。

1 个答案:

答案 0 :(得分:0)

如果在工作表上进行处理,处理大量数据可能会使您的过程费时费力,方法是用所有数据填充数组,然后更改其中的所有内容以最后将其粘贴回工作表。这是这样的:

Option Explicit

Sub FillColumns()

    Dim arrData As Variant, LastRow As Long, i As Long, ws As Worksheet

    Set ws = ThisWorkbook.Sheets("Sheet1") 'change the name of the sheet to the one you are doing the code

    With ws
        LastRow = .Cells(.Rows.Count, 3).End(xlUp).Row
        arrData = .Range("A2", .Cells(LastRow, "C")).Value
        For i = 1 To UBound(arrData)
            If arrData(i, 3) Like "Bus*" Then
                arrData(i, 1) = "BU CRM"
            Else
                arrData(i, 1) = "CSI ACE"
            End If
            If arrData(i, 3) Like "CSI*" Or arrData(i, 3) = vbNullString Then
                arrData(i, 2) = vbNullString
            Else
                arrData(i, 2) = Right(arrData(i, 3), 14)
            End If
        Next i
        .Range("A2", .Cells(LastRow, "C")).Value = arrData
    End With

End Sub