将多列中的数据复制到一列中

时间:2018-04-13 14:08:41

标签: excel vba

我有3列A,B,C,我希望在A,B,C中创建一个D列,但它应该包括"> =","< ="迹象也是如此。我正在处理的脚本确实帮助我循环列并将其数据复制到新列。任何人都可以帮我弄清楚如何在单元格中的数字开头添加这些特殊字符? 谢谢你的帮助。

Sub Try()

With ActiveWorkbook.Sheets("Sheet1")
    For rw = 1 To .Rows.Count
        If (.Rows(rw).Columns("A:A").Value <> "") Then
            .Rows(rw).Columns("A:A").Copy .Range("D" & rw)
        End If
    Next rw
    .Columns("A:A").Delete

End With

End Sub

enter image description here

4 个答案:

答案 0 :(得分:3)

使用cols A C 的数据,在 D1 中输入:

=IF(A1<>"",">="&A1,IF(B1<>"","<="&B1,C1))

并复制下来:

enter image description here

修改#1:

使用 VBA 执行此操作:

Sub PopulateFormulas()
    Dim N As Long, s As String

    s = "=IF(A1<>"""","">=""&A1,IF(B1<>"""",""<=""&B1,C1))"
    N = Range("A1").CurrentRegion.Rows.Count
    Range("D1:D" & N).Formula = s
End Sub

答案 1 :(得分:1)

可能不是最优雅的解决方案(你可能甚至不需要VBA,一个公式很可能就足够了),但这就行了:

Sub Test()

arr = Array(">=", "<=", "")

With ActiveWorkbook.Sheets("Sheet1")
    For cl = 1 To 3
        For rw = 2 To .Cells(ActiveSheet.Rows.Count, "C").End(xlUp).Row
            If .Cells(rw, cl).Value <> "" Then
                .Cells(rw, 4).Value = arr(cl - 1) & .Cells(rw, cl).Value
            End If
        Next rw
    Next cl
End With

'If you still need to delete those columns at the end-
'ActiveWorkbook.Sheets("Sheet1").Columns("A:C").Delete xlShiftLeft
End Sub

pic1

答案 2 :(得分:0)

这对我有用:

Sub macro_test()


k = 1

For k = 1 To 3
t = 2
lr = ActiveSheet.Cells(100000, k).End(xlUp).Row

Do Until t > lr

If Cells(t, k).Value = “” Then GoTo  continue

If k = 1 Then Cells(t, 4).Value = ">=" & Cells(t, k).Value
If k = 2 Then Cells(t, 4).Value = "<=" & Cells(t, k).Value
If k = 3 Then Cells(t, 4).Value = "" & Cells(t, k).Value
continue:
t = t + 1

Loop

Next

End Sub

答案 3 :(得分:0)

试试这个

Sub main()
    Dim iCol As Long, cell As Range, signs As Variant

    signs = Array(">=", "<=", "")
    For iCol = 1 To 3
        For Each cell In Columns(iCol).SpecialCells(xlCellTypeConstants, xlNumbers)
            cell.Value = signs(iCol - 1) & cell.Value                
        Next
    Next
End Sub

如果您的列A,B和C不是空单元格内容不仅仅是数字,那么您可以使用:

For Each cell In Columns(iCol).SpecialCells(xlCellTypeConstants)

如果它有一些公式,那么您可以使用:

For Each cell In Columns(iCol).SpecialCells(xlCellTypeFormulas)