我正在尝试创建一个嵌套的每个需要匹配C和C列中的值的内容。 E继续。 它总是改变所有价值观。如果C列中的“是”,但E列中的值不是南,则仍然会改变“是”的格式。
Sub LoopRange()
'Step 1: Declare your variables.
Dim MyRangeC As Range
Dim MyRangeE As Range
'Dim MyRange As Range
Dim MyCellC As Range
Dim MyCellE As Range
'Dim Cell As Range
'Dim M As Long
Dim N As Long
'Step 2: Define the target Range.
'M = Cells(1, 1).End(xlDown).Row
N = Cells(1, 1).End(xlDown).Row
Set MyRangeC = Range("C2:C" & N)
Set MyRangeE = Range("E2:E" & N)
'Step 3: Start looping through the range.
For Each MyCellE In MyRangeE
For Each MyCellC In MyRangeC
'Step 4: Do something with each cell.
If MyCellE.Value = "South" And MyCellC.Value = "Yes" Then
MyCellE.Font.Bold = True
MyCellC.Font.Italic = True
End If
'If MyCellE.Value = "North" And MyCellC.Value = "Yes" Then
'MyCellC.Font.Bold = True
'MyCellE.Font.Italic = True
'End If
'Step 5: Get the next cell in the range
Next MyCellC
Next MyCellE
'Next Cell
End Sub
以下是工作代码:
Sub LoopRange()
Dim N As Long
N = Cells(1, 1).End(xlDown).Row
For i = 2 To N
If Range("E" & i).Value = "South" And Range("C" & i).Value = "Yes" Then
Range("E" & i).Font.Bold = True
Range("C" & i).Font.Italic = True
End If
Next i
End Sub
答案 0 :(得分:4)
您不会逐行运行数据。相反,它会在C中为E中的每个单元格运行所有单元格。这意味着,您只需要一个" South"在E中改变所有"是"在C.
要解决此问题,您可以将循环更改为基于索引:
For i = 2 To N
If Range("E" & i).Value = "South" And Range("C" & i).Value = "Yes" Then
Range("E" & i).Font.Bold = True
Range("C" & i).Font.Italic = True
End If
Next i