我有一张excel表,其中包含A,B和C列中的值,如下所示:
A B C
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.
我想创建一个commandbutton
来执行以下工作:
对于每对线(包括一组),在它们下面插入2个新线,并用这样的值填充它们(假设我们正在处理驻留在第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
最终将新插入的线条的背景颜色设置为黄色。
你能帮我完成这项任务吗?
P.S。一旦按下这样的按钮,你会推荐什么Undo
能力?
答案 0 :(得分:5)
一些事情:
这应该让你开始。 SO上有很多人可以为你解决这个问题,但也许这可能是一个很好的问题,一次只能进入一点点;然后在库存特定细节时提出问题。
例如,如果您看到宏生成的代码看起来像ActiveSheet.Range("C2").Select
,您可能会问,“我看到如何选择单个单元格。如何选择整个行?”这将为您提供更有针对性的答案,帮助您解决问题。
答案 1 :(得分:1)
假设您的数据从第1行开始,命令按钮的名称是CommandButton1,请尝试在CommandButton1 click事件中添加以下代码。我使用自下而上的方法,因为在循环时我更容易处理行号。
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