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

时间:2017-11-23 05:15:11

标签: excel vba excel-vba

我没有太多使用Excel,也从不作为真正的电子表格/计算器。我给出了表格文本数据并根据一组规则对其进行格式化。到目前为止,这是可以手动管理的,但它变得笨拙,所以我想我会尝试自动化它。然后我查看了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"

我甚至找不到一个名为" cell"在模型中...

2 个答案:

答案 0 :(得分:1)

'对于每个细胞" x"在选定的范围内(在一列中)

Dim x as Range
For each x in selection

如果" x"不是空白

   if x <> "" then

每个细胞&#34; y&#34;在当前&#34; x&#34;

之后的选择中
  Dim y as range
  for each y in range(y.address & ":" & cells(selection.row.count,y.column).address)
编辑:发现错误!这应该是Range中的每个y(X.Offset(1,0).address等

如果&#34; y&#34; =&#34; x&#34;

中的文字
    If x.text = y.text then

更改&#34; y&#34;的格式向右,红色(&#34;是重复&#34;)&#39;不要问太多!

    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

如果&#34; x&#34;的FG颜色是蓝色的

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

更改&#34; x&#34;的格式向左,黑色(&#34;重复&#34;)

    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

答案 1 :(得分:0)

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

我确信有更好的方法来定义选择中当前单元格下面的“每个单元格”的范围“但这确实有效(删除了一些多余的东西)。

批评欢迎 - 这是我学习的方式。

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 A-Z
  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