更新表单不会导致行动,直到我运行vba模块两次

新的VBA我很困惑,为什么我需要运行我的模块两次,让它来更新我的单元格。 我的代码:

Option Explicit Sub m_Range_End_Method() Dim lRow As Long Dim lCol As Long Dim currentRow As Long Dim i As Integer Dim rng As Range Set rng = ActiveCell Range("B:B").Select lRow = Cells(Rows.Count, 1).End(xlUp).Row lCol = Cells(1, Columns.Count).End(xlToLeft).Column Sheets("MySheet").Select ' Loop Through Cells to set description in each cell Do While rng.Value <> Empty currentRow = ActiveCell.Row If InStr(rng.Value, "PETROL") = 0 Then Set rng = rng.Offset(1) rng.Select Else Worksheets("MySheet").Cells(currentRow, 5) = "Shopping" Worksheets("MySheet").Cells(currentRow, 6) = "Car" Set rng = rng.Offset(1) rng.Select End If Loop End Sub 

在第一次运行Excel 2016中发生的是B列突出显示,就是这样。 然后,我必须在Visual Basic编辑器中再次按下“运行”,然后更新列B取消select的所有条目。 我想要做的就是更新指定工作表的currentRow中的单元格。 我一直在阅读,但让自己陷入一些困惑,有人说我应该使用

 Range("B:B").Select 

声明和由于某种原因电子表格更新工作,但只有当我运行两次。 没有这个范围命令,出于我不明白的原因,电子表格不会更新 – 所有这一切发生的是,select框移动到与石油的条目,并停留在那里程序运行,但不更新。

这个程序的目的是在表格中查找B列中所有出现的单词,在这个最初的例子中是PETROL(我将要扩展到包括许多其他的)。 对于同一行上的匹配,我希望它用列表更新第5列和第6列。 Excel电子表格将有数百行的条目在B列中有不同的描述。

任何帮助将非常感激。

我猜你必须运行两次,因为第一次运行它, ActiveCell可能是任何东西,你的循环取决于它不是空的开始,但第一次运行后,你已经select列B(和其他东西) …

阅读以前的回答,避免使用SelectActivate ,这将使您的代码更健壮: 如何避免使用Excel中selectVBAmacros


修订的代码

请参阅评论的详细信息,这里是一个清洁版本的代码,应该第一次/每次工作!

 Sub m_Range_End_Method() Dim col As Range Dim rng As Range Dim currentRow As Long ' Use a With block to 'Fully Qualify' the ranges to MySheet With ThisWorkbook.Sheets("MySheet") ' Set col range to the intersection of used range and column B Set col = Intersect(.UsedRange, .Columns("B")) ' Loop through cells in col to set description in each row For Each rng In col currentRow = rng.Row ' Check upper case value match against upper case string If InStr(UCase(rng.Value), "PETROL") > 0 Then .Cells(currentRow, 5) = "Shopping" .Cells(currentRow, 6) = "Car" End If Next rng End With End Sub