セルを手動でコピー/貼り付け/切り取り/挿入すると問題が発生し、回避するのは困難です。
VBAマクロを使用して問題を解決しました。
セルを手動でコピー/貼り付け/切り取り/挿入する代わりに、Excelのマクロを使用してセル範囲を保持します(ボタンでアクティブ化)。
Sub addAndBtnClick()
Set Button = ActiveSheet.Buttons(Application.Caller)
With Button.TopLeftCell
ColumnIndex = .Column
RowIndex = Button.TopLeftCell.Row
End With
currentRowIndex = RowIndex
Set Table = ActiveSheet.ListObjects("Table name")
Table.ListRows.Add (currentRowIndex)
Set currentCell = Table.DataBodyRange.Cells(currentRowIndex, Table.ListColumns("Column name").Index)
currentCell.Value = "Cell value"
Call setCreateButtons
End Sub
Sub removeAndBtnClick()
Set Button = ActiveSheet.Buttons(Application.Caller)
With Button.TopLeftCell
ColumnIndex = .Column
RowIndex = Button.TopLeftCell.Row
End With
currentRowIndex = RowIndex
Set Table = ActiveSheet.ListObjects("Table name")
Table.ListRows(currentRowIndex - 1).Delete
End Sub
Sub setCreateButtons()
Set Table = ActiveSheet.ListObjects("Table name")
ActiveSheet.Buttons.Delete
For x = 1 To Table.Range.Rows.Count
For y = 1 To Table.Range.Columns.Count
If y = Table.ListColumns("Column name").Index Then
Set cell = Table.Range.Cells(x, y)
If cell.Text = "Some condition" Then
Set btn = ActiveSheet.Buttons.Add(cell.Left + cell.Width - 2 * cell.Height, cell.Top, cell.Height, cell.Height)
btn.Text = "-"
btn.OnAction = "removeAndBtnClick"
Set btn = ActiveSheet.Buttons.Add(cell.Left + cell.Width - cell.Height, cell.Top, cell.Height, cell.Height)
btn.Text = "+"
btn.OnAction = "addAndBtnClick"
End If
End If
Next
Next
End Sub
フォーマットをリセットするには(実際には必要ありません):
Sub setCondFormat()
Set Table = ActiveSheet.ListObjects("Table name")
Table.Range.FormatConditions.Delete
With Table.ListColumns("Column name").DataBodyRange.FormatConditions _
.Add(xlExpression, xlEqual, "=ISTLEER(A2)") 'Rule goes here
With .Interior
.ColorIndex = 3 'Formatting goes here
End With
End With
...
End Sub