我将参考下图:
我试图将 FirstValue 列拆分为它右侧的两列;但是,我想根据 Parameter 列拆分列。当 Parameter 值为奇数时,我只想将值复制到 OtherValue1 列。当参数值是偶数时,我只想将值复制到 OtherValue2 列。在阅读论坛并尝试了 excel 的“文本到列”功能后,我找不到解决方案。
有没有办法使用 VBA 实现这一点?
*注意:工作表实际上大约有 10,000 行长,因此速度也会有所帮助。
编辑:这是我到目前为止的代码。我在这行代码中遇到对象错误:.Cells(2, MF1Col).Formula = "=IF(MOD(paraformula,2)=1,WTRfor,"")"
Dim rw As Worksheet
Dim secondCell, MF1Cell, MF2Cell, paraCell, MF1formula, MF2formula, paraformula, WTRfor As Range
Dim secondCol As Long, MF1Col As Long, MF2Col As Long, paraCol As Long
Set rw = ActiveSheet
With rw
Set secondCell = .Rows(1).Find("FirstValue”)
' Check if the column with “FirstValue” is found
'Insert Two Columns after FirstValue
If Not secondCell Is Nothing Then
secondCol = secondCell.Column
.Columns(secondCol + 1).EntireColumn.Insert
.Columns(secondCol + 2).EntireColumn.Insert
.Cells(1, secondCol + 1).Value = "OtherValue1"
.Cells(1, secondCol + 2).Value = "OtherValue2"
.Activate
Set MF1Cell = .Rows(1).Find("OtherValue1")
MF1Col = MF1Cell.Column
Set MF2Cell = .Rows(1).Find("OtherValue2")
MF2Col = MF2Cell.Column
Set paraCell = .Rows(1).Find("Parameter")
paraCol = paraCell.Column
Set paraformula = Range(.Cells(2, paraCol).Address(RowAbsolute:=False, ColumnAbsolute:=False))
Set MF1formula = Range(.Cells(2, MF1Col).Address(RowAbsolute:=False, ColumnAbsolute:=False))
Set WTRfor = Range(.Cells(2, secondCol).Address(RowAbsolute:=False, ColumnAbsolute:=False))
.Cells(2, MF1Col).Formula = "=IF(MOD(" & paraformula & ",2)=1," & WTRfor & ","""")"
Range(.Cells(2, MF1Col).Address).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveSheet.Paste
Set MF2formula = Range(.Cells(2, MF2Col).Address(RowAbsolute:=False, ColumnAbsolute:=False))
.Cells(2, MF2Col).Formula = "=IF(MOD(" & paraformula & ",2)=0," & WTRfor & ","""")"
Range(.Cells(2, MF2Col).Address).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveSheet.Paste
End If
End With