如果我在 Excel 中有以下内容:
A B C (columns)
a b c (data)
d e f (data)
g h i (data)
- - - (empty)
以及以下验证下拉列表:
With rng.Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="1,2"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
首先,我需要使用 vba 检查单元格是否有数据,如果有,则在新列/单元格的左侧添加验证下拉列表,如下所示:
A B C D
1,2 a b c
1,2 d e f
1,2 g h i
- - - -
在用户从下拉列表中选择一个值之后,我需要第二个宏来根据所选值在现有列的任一侧添加更多列:
A B C D E F G
1 a 1 b 1 c 1 (if 1 selected from dropdown)
2 d 2 e 2 f 2 (if 2 selected from dropdown)
2 g 2 h 2 i 2 (if 2 selected from dropdown)
我是 vba 的真正初学者,因此非常感谢任何帮助。
======= 编辑 =================================
我已经解决了第一部分,其余部分仍然很痛苦:
Sub changeClass()
Dim rng As Range
Dim r As Range
Set rng = Range(Cells(6, 2), Cells(6, 2).End(xlDown))
Dim rCell As Range
For Each rCell In rng.Cells
rCell.Offset(0, -1).Value = "Data"
Next rCell
For Each rCell In rng.Cells
With rng.Offset(0, -1).Validation
.Delete
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:="=$A$1:$A$3"
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With
Next rCell
End Sub
以及如何插入新列,但不能插入新数据:
Sub newColumn()
Dim rng As Range
Dim crng As Range
Dim r As Range
With ActiveSheet
LastCol = .Cells(5, .Columns.Count).End(xlToLeft).Column
End With
Set rng = Range(Cells(6, 1), Cells(6, 1).End(xlDown))
Set crng = Range(Cells(5, 1), Cells(5, LastCol))
Set drng = Range(Cells(4, 1), Cells(4, LastCol))
Dim rCell As Range
Dim cCell As Range
Dim dCell As Range
For Each rCell In rng.Cells
For Each cCell In crng.Cells
cCell.Offset(-1, 0).Value = "columnMark"
Next cCell
Next rCell
For Each dCell In drng.Cells
If dCell.Value = "columnMark" Then
dCell.EntireColumn.Offset(0, 1).Insert
End If
dCell.Value = ""
Next dCell
End Sub