帮助我在Excel中自动化一个过程

我有一个excel工作表,在列A,B和C中的值是这样的:

ABC 1 8.22 1.99902 32.48974 2 8.22 3.04698 33.92426 3 8.22 2.26374 33.1547 4 8.22 2.78227 33.2593 6 8.22 2.46798 33.34269 6 8.22 2.57802 33.67131 7 8.22 2.46798 32.7427 8 8.22 2.57802 33.07131 

还有一个单元格(比如说F1)包含的值只能是1,2或3。

我想要创build一个commandbuttonbutton来执行以下工作:对于每一对行(它们都是一个组),在它们下面插入两行新的行,并用这样的值填充它们(假设我们正在处理位于第9行的组和10)

 If F1 = 1 THEN A11 = A10 B11 = B10 C11 = C9 A12 = A10 B12 = B9 C12 = C10 If F1 = 2 THEN A11 = A10 B11 = B10 C11 = C9 A12 = A9 B12 = B10 C12 = C10 If F1 = 3 THEN A11 = A10 B11 = B9 C11 = C10 A12 = A9 B12 = B10 C12 = C10 

最后,将新插入的行的背景颜色设置为黄色。

你能帮我完成这个任务吗?

PS一旦像这样的button被按下,你会推荐一个Undofunction?

假设您的数据从第1行开始,并且命令button的名称是CommandButton1,请尝试在CommandButton1单击事件中添加以下代码。 我使用了自下而上的方法,因为在循环时处理行号更容易。

 Private Sub CommandButton1_Click() Dim lines_count As Integer Dim fixed_column As Integer Dim i As Integer lines_count = Application.WorksheetFunction.Count(Range("A:A")) fixed_column = Range("F1").Value For i = lines_count + 2 To 4 Step -2 Rows(i - 1 & ":" & i).Select Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove Select Case fixed_column Case 1 Cells(i - 1, 1).Value = Cells(i - 2, 1).Value Cells(i, 1).Value = Cells(i - 2, 1).Value Cells(i - 1, 2).Value = Cells(i - 2, 2).Value Cells(i, 2).Value = Cells(i - 3, 2).Value Cells(i - 1, 3).Value = Cells(i - 3, 3).Value Cells(i, 3).Value = Cells(i - 2, 3).Value Case 2 Cells(i - 1, 1).Value = Cells(i - 2, 1).Value Cells(i, 1).Value = Cells(i - 3, 1).Value Cells(i - 1, 2).Value = Cells(i - 2, 2).Value Cells(i, 2).Value = Cells(i - 2, 2).Value Cells(i - 1, 3).Value = Cells(i - 3, 3).Value Cells(i, 3).Value = Cells(i - 2, 3).Value Case 3 Cells(i - 1, 1).Value = Cells(i - 2, 1).Value Cells(i, 1).Value = Cells(i - 3, 1).Value Cells(i - 1, 2).Value = Cells(i - 3, 2).Value Cells(i, 2).Value = Cells(i - 2, 2).Value Cells(i - 1, 3).Value = Cells(i - 2, 3).Value Cells(i, 3).Value = Cells(i - 2, 3).Value End Select Range("A" & CStr(i - 1) & ":C" & CStr(i)).Select Selection.Interior.ColorIndex = 6 Next End Sub 

一些东西:

  • 你应该尝试创buildmacros,然后看看他们产生了什么样的代码。 这将帮助您看到需要什么VBA代码来操纵Excel表单。
  • 创build几个macros之后,学习如何执行循环,以便可以为所需的所有单元多次运行该进程。
  • 您无法撤消macros的结果。 您可能会尝试编写一个单独的函数来撤销之前函数的结果,但听起来像是一大堆工作。 我build议您创build一个工作表的副本,并为您的开发阶段使用新工作表。

这应该让你开始。 有很多人可以为你解决这个问题,但也许这是一个很好的问题, 然后在您存储特定细节时提问。

例如,如果您看到由macros看起来像ActiveSheet.Range("C2").Select生成的代码,请ActiveSheet.Range("C2").Select ,您可能会问,“我看如何select一个单元格,如何select整个行? 这会让你更有针对性的答案来帮助你解决你的问题。