VBA根据单元格

时间:2017-09-19 18:49:00

标签: excel vba excel-vba

我正在尝试完成以下任务,请参阅图片以供参考。

正如您在C,D和E列中看到的那样,分别有X55.656Y922.495等文字,依此类推。现在我面临的问题是带有“X”的文本应该放在X列中,而以“Y”开头的文本应该放在Y列中。必须对包含XY的所有行执行此操作。你能从头开始为我编写一个VBA代码来帮助解决我的问题吗?

enter image description here

输出应如下图所示,

enter image description here

1 个答案:

答案 0 :(得分:1)

您需要说明如何处理同一行中多个源列中出现的X或Y.

如果你不介意在连续多次出现X或Y时覆盖,你可以使用以下作为起点:

Dim wb as workbook
Dim ws as worksheet
Dim LastRow as long
Dim rng as Range
Dim row as Range
Dim cell as Range

Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheetname") 'change as appropriate

'Assuming column C, D  and E have end items in the same row (otherwise consider finding lastrow using current region. 
LastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).row
Set rng = ws.Range(ws.Cells(1, "C"), ws.Cells(LastRow, "E"))

For Each row in rng.Rows
    For Each cell in row.cells
        If Lcase(Left(cell.Value,1)) = "x" Then
            If Mid(cell.Address, 2, 1) = "C" Then
                cell.Offset(0, 21) = cell.Value
            Elseif Mid(cell.Address, 2, 1) = "D" Then
                cell.Offset(0, 20) = cell.Value
            Else: cell.Offset(0, 19) = cell.Value
            End If
            cell.clearcontents
        End If
        If Lcase(Left(cell.Value,1)) = "y" Then
            If Mid(cell.Address, 2, 1) = "C" Then
                cell.Offset(0, 22) = cell.Value
            Elseif Mid(cell.Address, 2, 1) = "D" Then
                cell.Offset(0, 21) = cell.Value
            Else: cell.Offset(0, 20) = cell.Value
            End If
            cell.clearcontents
        End If
    Next Cell
Next row
End Sub

查找LastRow Finding LastRow

的不同方法