我是VBA的新手 - 完全是外语,尽我所能去理解。
我正在尝试编写一段代码,它将帮助我根据另一个工作表中表格中单元格的内部颜色格式对一个工作表中的项目进行颜色编码。我已经在基本级别实现了它,但是当用于颜色编码的单元格的值无法匹配Sheet2中表格中的任何值时,它就会失效。理想情况下,我希望它在这个例子中做的只是向下移动到单元格1行并继续循环,但实际发生的是它在Sheet2中围绕桌子循环寻找匹配。我尝试过各种Else和ElseIf语句试图阻止它,但它们都没有产生预期的结果。我写的代码(很糟糕,我确定)如下:
Sub Colour_Code_Cells()
Dim xlRange As Range
Dim xlCell As Range
Dim xlSheet As Worksheet
Dim formatSheet As Worksheet
Dim formatRange As Range
Dim formatCell As Range
Set xlSheet = ActiveWorkbook.Worksheets("colourcode")
Set xlRange = xlSheet.Range("A1:A10")
Set formatSheet = ActiveWorkbook.Worksheets("Sheet1")
Set formatCell = formatSheet.Range("A2")
formatCell.Activate
Do Until Selection.Value = ""
For Each xlCell In xlRange
If xlCell.Value = ActiveCell.Value Then
ActiveCell.Interior.Color = xlCell.Interior.Color
ActiveCell.Offset(1, 0).Select
End If
Next xlCell
Loop
End Sub
任何建设性的提示都会非常感激。如果它已经查看了一次,你怎么告诉它停止查看每个Next xlCell ???
非常感谢提前
答案 0 :(得分:0)
主要问题是你在If语句中有xlRange
,所以如果它在Sub Colour_Code_Cells()
Dim xlRange As Range
Dim xlCell As Range
Dim xlSheet As Worksheet
Dim formatSheet As Worksheet
Dim formatRange As Range
Dim formatCell As Range
Dim t As Long
Set xlSheet = ActiveWorkbook.Worksheets("colourcode")
Set xlRange = xlSheet.Range("A1:A10")
Set formatSheet = ActiveWorkbook.Worksheets("Sheet1")
With formatSheet
For Each formatCell In .Range("A2", .Cells(.Rows.Count, 1).End(xlUp))
t = 0
On Error Resume Next
t = Application.WorksheetFunction.Match(formatCell, xlRange, 0)
On Error GoTo 0
If t > 0 Then
formatCell.Interior.Color = xlRange(t).Interior.Color
End If
Next formatCell
End With
End Sub
中找不到匹配项,它将不会移动到下一个单元格并继续检查同一个单元格。因此无限循环。
选择并激活会减慢代码速度,通常不需要,应该避免使用。
代码的小型重构将使其更快更可靠。
这将通过一个循环使用匹配来找到匹配:
//Thread Practice
//one number ,one char ,one string comining these two parallely
class Thread_1 extends Thread {
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + "... " + i);
try {
Thread.sleep(1000);
}
catch (InterruptedException ex) {
}
}
}
}
class Thread_2 extends Thread {
String s = new String("ABCDEFGHIJ");
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + ".. " + s.charAt(i));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
class Thread_3 extends Thread {
String s = new String("ABCDEFGHIJ");
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getId() + ".. " + i + s.charAt(i));
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
class Practice {
public static void main(String[] args) {
Thread_1 t1 = new Thread_1();
Thread_2 t2 = new Thread_2();
Thread_3 t3 = new Thread_3();
t1.start();
t2.start();
t3.start();
}
}