如下创建列

时间:2018-12-11 12:41:12

标签: excel vba excel-vba

我在Excel中有两列

col1    col2
NA      Missing
12      Pass
NA      Missing

因此,我需要生成col3,好像Missing然后提及Missing 否则取值“ 12”。 如下所示:

col3
Missing
12
Missing

如何在VBA中执行此操作? 注意:我需要获取格式,不仅是值 我试图将所有值存储在数组中,然后在excel中显示,但是它不起作用,甚至我都需要格式

Set cw = Worksheets("5").Range("G15:G17")
For Each cwVal In cw
If cwVal = "Missing" Then
    ReDim Preserve arr(i)
    arr(i) = cwVal
    i = i + 1
Else
    ReDim Preserve arr(i)
    arr(i) = cwVal
    i = i + 1
End If
Next cwVal
Worksheets("Summary").Range("G6:G8") = arr()

2 个答案:

答案 0 :(得分:0)

让我们为您提供一个带有选择大小写的循环,这样您就可以知道要复制的内容(保留格式)并只需粘贴复制的单元格即可:

dim i as long, lr as long
with sheets("5") 'assuming this is maintained
    lr = .cells(.rows.count,1).end(xlup).row 'dynamically finds last row in sheet
    for i = 2 to lr 'assumes row 1 is headers
        select case .cells(i,2).value
            case "missing"
                .cells(i,2).copy
            case else
                .cells(i,1).copy
        end select
        .cells(i,3).pastespecial paste:=xlpastevaluesandnumberformats
    next i
end with

从我的头上写下这个,未经测试


edit1:回到并使用.pastespecial保留格式格式...当我本来是错误的.paste

时,忘记了这一点

答案 1 :(得分:0)

尝试:

Option Explicit

Sub test()

Dim i As Long, j As Long

    With ThisWorkbook.Worksheets("5")

        j = 6

        For i = 15 To 17

            If .Range("G" & i).Value = "Missing" Then
                .Range("G" & j).Value = "Missing"
            Else
                .Range("G" & j).Value = .Range("F" & i).Value
            End If

            j = j + 1

        Next i

    End With

End Sub