I am trying to create a worksheet that will create columns depending on the value of a cell. So if I input 10 as the value, 10 columns will be created with the appropriate formulas. I was able to achieve that, however, I would like the range to pull a value from a different worksheet. I wasn't sure if that was possible and if so, how to do it. If it is not, is there a way to have the sheet that I want the columns to appear on refresh once I enter the value on the other sheet, so I can link that value to each sheet it is needed? I will have multiple sheets that will depend on this value to display information. For example, as noted above, if I enter 10 on sheet 1 then on sheets 2 thru 15, 10 columns will be created with their own formatting depending on the sheet requirements.
VBA Code:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
Dim KeyCells As Range, ColNum As Long, TotalCol As Long, LeftFixedCol As Long
Dim Rng As Range, c As Range
Set KeyCells = Range("B2")
If Application.Intersect(KeyCells, Target) Is Nothing Then Exit Sub
If IsNumeric(KeyCells.Value) = False Then Exit Sub
ColNum = KeyCells.Value
If ColNum <= 0 Then Exit Sub
Set Rng = Range(Cells(4, 1), Cells(4, Columns.Count))
Set c = Rng.Find("END")
If c Is Nothing Then Exit Sub
TotalCol = c.Column
LeftFixedCol = 1
Dim i As Integer
If TotalCol < LeftFixedCol + ColNum + 1 Then
For i = TotalCol To LeftFixedCol + ColNum
Columns(i).Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Cells(4, i).Value = "Member" & i - LeftFixedCol
Cells(5, i).Value = "=DATA!$A$2"
Cells(6, i).Value = "=OFFSET(DATA!$C$2,COLUMN()-2,0)"
Cells(7, i).Value = "=OFFSET(DATA!$D$2,COLUMN()-2,0)"
Cells(8, i).Value = "=OFFSET(DATA!$E$2,COLUMN()-2,0)"
Cells(10, i).Value = "=OFFSET(DATA!$F$2,COLUMN()-2,0)"
Cells(12, i).Value = "=OFFSET(DATA!$G$2,COLUMN()-2,0)"
Cells(13, i).Value = "=OFFSET(DATA!$H$2,COLUMN()-2,0)"
Cells(14, i).Value = "=OFFSET(DATA!$I$2,COLUMN()-2,0)"
Next i
End If
If TotalCol > LeftFixedCol + ColNum + 1 Then
For i = TotalCol - 1 To LeftFixedCol + ColNum + 1 Step -1
Columns(i).Delete
Next i
End If
End Sub