将excel vba应用于整个列而不是单个单元格

时间:2017-10-20 10:39:04

标签: excel excel-vba vba

您好我想将以下vba应用于整个列AK而不仅仅是AK1

Sub Tidy_Cell()
Range("AK1") = Replace(Range("AK1"), Chr(13), "")
For x = 1 To Len(Range("AK1"))
    If Mid(Range("AK1"), x, 1) = Chr(10) And Mid(Range("AK1"), x + 1, 1) = Chr(10) Then

    Range("AK1") = Left(Range("AK1"), x) & Mid(Range("AK1"), x + 2)

    End If
    Next
With Range("A1")
    .Value = Mid(.Value, 1)
    .VerticalAlignment = xlTop
End With
End Sub

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

我会将所有代码放入一个检查列AK

的循环中
dim lLastUsed As Long
lLastUsed = Cells(1048576, "AK").End(xlUp).Row
For i = 1 to lLastused

    //insert your code here

Next i

请记住您将其定义为Range(“AK1”)的每个位置,您需要将其更改为Range(“AK”& i),因此它最终会出现如下情况:

Sub Tidy_Cell()
Dim lLastUsed As Long
lLastUsed = Cells(1048576, "AK").End(xlUp).Row
For i = 1 to lLastUsed
  Range("AK" & i) = Replace(Range("AK" & i), Chr(13), "")
  For x = 1 To Len(Range("AK" & i))
    If Mid(Range("AK" & i), x, 1) = Chr(10) And Mid(Range("AK" & i), x + 1, 1) = Chr(10) Then

      Range("AK" & i) = Left(Range("AK" & i), x) & Mid(Range("AK" & i), x + 2)

    End If
  Next x
Next i

With Range("A1")
  .Value = Mid(.Value, 1)
  .VerticalAlignment = xlTop
End With
End Sub

希望这可以帮助你