VBA循环不返回任何值,加上无法终止

我已经写了一些代码,旨在search列中的单元格,看它们是否以某个string开始,然后根据另一列中的string返回一个值。 我有两个问题,首先循环实际上并没有返回列中的任何值8,9,10或11.第二个循环不停止运行? 这是我的代码

Sub Possible_solution_one() Dim i As Integer Dim j As Integer Dim ws As Worksheet Set ws = ActiveSheet For i = 2 To ws.Cells(ws.Rows.Count, "a").End(xlUp).Row Do While Cells(i, 1).Value <> "" If Cells(i, 2) = "Business://EXTRACTS/" & "*" Then Cells(i, 8) = "OBS(" & Cells(i, 2).Value & ",SHARE,#DI) OR " End If i = i + 1 Loop Next For j = 2 To ws.Cells(ws.Rows.Count, "a").End(xlUp).Row Do While Cells(j, 6).Value <> "" If Cells(j, 6) = "Business" & "*" Then Cells(j, 9) = "OBS(" & Cells(j, 4).Value & ",SHARE,DI) OR " ElseIf Cells(j, 6) = "CSTM" Then Cells(j, 10) = "PUM(" & Cells(j, 4).Value & ",#D7) OR " ElseIf Cells(j, 6) = "*FS" Then Cells(j, 11) = "FCON(" & Cells(j, 4).Value & ") OR " End If i = i + 1 Loop Next End Sub 

为了给出这种情况,我在B列中有一种types的string,而在F列中有三种types的string。我们希望根据b和D在第8,9,10,11列中返回不同的东西

如果您使用通配符进行模式匹配 ,则需要使用Like运算符。 例如, If Cells(i, 2) Like "Business://EXTRACTS/" & "*" Then

For While循环中的Do While循环是不必要的。 在For … Next循环中手动增加递增计数器也不是一个好主意。

第二个循环是永远运行的,因为你增加了 ,而不是j

Select Case语句将更适合第二个j循环中的多个条件。

 Sub Possible_solution_one() Dim i As Long, j As Long Dim ws As Worksheet Set ws = ActiveSheet With ws For i = 2 To .Cells(.Rows.Count, "a").End(xlUp).Row If Not CBool(Len(Cells(i, "a").Value)) Then Exit For If .Cells(i, 2) = "Business://EXTRACTS/" & "*" Then .Cells(i, 8) = "OBS(" & .Cells(i, 2).Value & ",SHARE,#DI) OR " End If Next i For j = 2 To .Cells(ws.Rows.Count, "a").End(xlUp).Row Select Case .Cells(j, 6).Value Case "Business*" .Cells(j, 9) = "OBS(" & Cells(j, 4).Value & ",SHARE,DI) OR " Case "CSTM" .Cells(j, 10) = "PUM(" & Cells(j, 4).Value & ",#D7) OR " Case "*FS" .Cells(j, 11) = "FCON(" & Cells(j, 4).Value & ") OR " End If End Select Next j End With End Sub 

我还join了一个With … End With语句将所有单元格关联到父级ws工作表。 注意Cells而不是Cells 。 前缀周期将参数分配给With … End With中引用的工作表。

没有样本数据,我不能完全testing这个重写,但它确实编译。

你的第二个while循环使用i = i + 1而不是j = j + 1,所以它不会增加单元格(j,6).value如果单元格中有任何东西(j,6),那么循环不会停止赛跑

 For j = 2 To ws.Cells(ws.Rows.Count, "a").End(xlUp).Row Do While Cells(j, 6).Value <> "" If Cells(j, 6) = "Business" & "*" Then Cells(j, 9) = "OBS(" & Cells(j, 4).Value & ",SHARE,DI) OR " ElseIf Cells(j, 6) = "CSTM" Then Cells(j, 10) = "PUM(" & Cells(j, 4).Value & ",#D7) OR " ElseIf Cells(j, 6) = "*FS" Then Cells(j, 11) = "FCON(" & Cells(j, 4).Value & ") OR " End If 'i = i + 1 j = j + 1 Loop Next