如何根据前一列更改位数?

时间:2014-11-25 20:06:27

标签: excel-vba foreach conditional-formatting vba excel

这构建了这个问题Using Left without Copy & Paste

我需要根据之前列中的公司有条件地格式化这些列。这是有效的编码:

Sub keep12()
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")

Dim rng As Range
Set rng = wks.Range("C3:C" & wks.Range("C" & wks.Cells.Rows.Count).End(xlUp).Row)

'set column C as Number (if this step is skipped it can go to Scientific and that doesn't work)
Columns("C:C").Select
Application.CutCopyMode = False
Selection.NumberFormat = "0.00"
Selection.NumberFormat = "0"

For Each Cell In rng
    Cell.Value = Left(Cell.Text, 12)
Next Cell
End Sub

基本上我想更进一步,如果B列(公司代码)是ABC,DEF或GHI,那么将C旁边的单元格格式化为10位数,对于B列中的任何其他信息(JKL,然后将MNO设置为12.我猜我可以使用For Each,Select Case这样的东西吗?但我不完全确定如何做到这一点。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

Sub keep12()
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")

Dim rng As Range
Set rng = wks.Range("C3:C" & wks.Range("C" & wks.Cells.Rows.Count).End(xlUp).Row)

'set column C as Number (if this step is skipped it can go to Scientific and that doesn't work)
Columns("C:C").Select
Application.CutCopyMode = False
Selection.NumberFormat = "0.00"
Selection.NumberFormat = "0"

For Each cell In rng
    Select Case cell.Offset(0, -1)
    Case "ABC", "DEF", "GHI"
        cell.Value = Left(cell.Text, 10)
    Case Else
        cell.Value = Left(cell.Text, 12)
    End Select
Next cell
End Sub