打破VBA循环

我相信这很简单,我只是无法在网上find任何东西。

我正在写一个macros来格式化XL电子表格,我从第三方应用程序下载。 他们来格式化所有古怪的,所以我试图让它更容易从我们需要的数据。

这是一个简单的VBA Do循环,使列BL中的单元格更新。 这些单元格中的数据包含换行符,直到双击单元格才显示出来。 下面的VBA导致对单元格的更新达到相同的效果,只是工作量less。 然而,它目前崩溃的Excel,我不明白为什么。 它在单个实例中工作,但是当我循环 – BOOM! – 冷冻。 任何帮助将被温和赞赏。

Sub updateCell() Dim currentValue As String ActiveSheet.Range("BL1").Select Do Until ActiveCell.Value = "" ActiveCell.Offset(1, 0).Select currentValue = ActiveCell().Value ActiveCell().Value = currentValue & "" Loop End Sub 

尝试一些更直接的东西:

 With ActiveSheet lrow = .Range("BL" & .Rows.Count).End(xlUp).Row '~~> find last row on BL With .Range("BL1:BL" & lrow) '~~> work on the target range .Value = .Value '~~> assign its current value to it End With End With 

上面的代码就像手动按F2然后按Enter键

编辑1:获取最后一行的说明

 ActiveSheet.Rows.Count '~~> Returns the number of rows in a sheet which is 1048576 MsgBox ActiveSheet.Rows.Count '~~> run this to confirm 

所以这条线实际上将BL连接到1048576

 .Range("BL" & .Rows.Count) '~~> Count is a property of the Rows Collection 

与…一样:

 .Range("BL" & 1048576) 

和:一样

 .Range("BL1048576") 

然后到最后一行,我们使用Range Object End Method

 .Range("BL" & .Rows.Count).End(xlUp) 

所以基本上,上面的代码转到单元格BL1048576,然后像手动按Ctrl + 向上箭头
要返回范围的实际行号,我们使用Range Object Row属性

 lrow = .Range("BL" & .Rows.Count).End(xlUp).Row 

在这里看到更多关于声明
它具有与你的代码相同的效果,没有循环。 HTH

但是,如果你想要删除单元格上Alt + Enter生成的换行符 ,请尝试以下方法:

 Dim lrow As Long, c As Range With ActiveSheet lrow = .Range("BL" & .Rows.Count).End(xlUp).Row For Each c In .Range("BL1:BL" & lrow) c.Value = Replace(c.Value, Chr(10), "") Next End With 

其中Chr(10)等同于使用replace函数replace为"" 换行符