需要使用Excel VBA对象模型进行快速入门

我不用Excel工作太多,也从来没有真正的电子表格/计算器。 我给出了列表的文本数据,并根据一组规则进行格式化。 到目前为止,这已经可以手动pipe理,但它变得笨重,所以我想我会尝试自动化它。 然后,我看着Excel对象模型和…哇。

我没有任何困难,但是插入正确的对象,方法等是一个噩梦。 我很感谢在这方面的帮助。 这是逻辑/伪代码:

for each cell "x" in a selected range (in a single column) if "x" is not blank for each cell "y" in selection after current "x" if text in "y" = text in "x" change format of "y" to right, red ("is a repeat") if FG color of "x" is blue change format of "x" to left, black ("is repeated") end if end if end if next "y" next "x" 

我甚至无法在模型中find名为“单元格”的对象…

'对于选定范围内的每个单元格“x”(在单个列中)

 Dim x as Range For each x in selection 

如果“x”不是空白

  if x <> "" then 

在当前“x”之后select每个单元“y”

  Dim y as range for each y in range(y.address & ":" & cells(selection.row.count,y.column).address) 

编辑:发现错误! 这应该是在范围(X.Offset(1,0).address等的每个y

如果“y”中的文本=“x”中的文本

  If x.text = y.text then 

将“y”的格式改为正确,红色(“是重复”)“不要问太多!

  y.NumberFormat = "[Red]" & Chr$(34) & "Is a Repeat" & Chr$(34) & ";[Red]" & Chr$(34) & "Is a Repeat" & Chr$(34) & ";[Red]" & Chr$(34) & "Is a Repeat" & Chr$(34) & ";[Red]" & Chr$(34) & "Is a Repeat" & Chr$(34) 

End Sub y.Horizo​​ntalAlignment = xlright

如果“x”的FG颜色是蓝色的

  if x.interior.color = vbblue then'or use rgb function 

将“x”的格式更改为左侧,黑色(“重复”)

  x.NumberFormat = Chr$(34) & "Is a Repeat" & Chr$(34) & ";" & Chr$(34) & "Is a Repeat" & Chr$(34) & ";" & Chr$(34) & "Is a Repeat" & Chr$(34) & ";" & Chr$(34) & "Is a Repeat" & Chr$(34) x.horizontalalignment = xlright end if end if end if next y next x 

感谢这里提供的线索,我设法做到这一点 – 没有深入的了解如何。 ( – :

我相信有更好的方法来定义“select中的当前单元格”下面的“每个单元格”的范围,但这是行得通的(删除了一些多余的东西)。

批评欢迎 – 这是我如何学习。

 Sub FormatColors() Dim Outer As Range Dim Inner As Range Dim txtColumn As String Dim RangeEnd As String Dim txtInner As String With Selection txtColumn = Chr(.Column + 64) 'limited to AZ RangeEnd = ":" & txtColumn & Trim(Str(.Row + .Rows.Count)) .Font.Color = vbBlue .Cells.HorizontalAlignment = xlCenter End With For Each Outer In Selection If Not IsEmpty(Outer) Then txtInner = txtColumn & Trim(Str(Outer.Row + 1)) & RangeEnd For Each Inner In Range(txtInner) If Inner.Text = Outer.Text Then Inner.HorizontalAlignment = xlRight Inner.Font.Color = vbRed If Outer.Font.Color = vbBlue Then Outer.HorizontalAlignment = xlLeft Outer.Font.Color = vbBlack End If End If Next End If Next End Sub