【发布时间】:2013-03-26 16:39:24
【问题描述】:
如果我在 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
【问题讨论】:
-
我尝试了各种方法; xlLeft 是我放入各种组合的组合,Offset(0, -1) 是另一种组合,但我不知道如何将它应用到带有数据单元格的整个列。似乎没有什么对我有用。
-
在您看来这会是一件大事吗?谢谢。
-
您真的需要动态创建列吗?是否可以从 7 列开始,将数据放在
B、D和F列中,并在A列中的单元格中下拉,然后在C、@987654332 列中添加列@ 和G跟列A?您可以在没有任何 VBA 的情况下实现这一目标。 -
Excel 是否适合您正在尝试做的事情?也许数据库会更好,比如 Microsoft Access?
-
不幸的是,在这种情况下,列数可能会有所不同,因此无法确定会有多少列。对 Excel 的需求也是不可避免的,因为这是最终用户将拥有的,我无法让他们使用其他程序。