I want to copy an adapted version of a subset of the headers' row of one workbook to a new workbook using VBA.
Initially, my idea was to:
- Read original header row range into an array of strings variable
- Manipulate the array, namely dropping/eliminating and adding some entries
- Write the transformed array to the destination location/workbook
Since I was unable to find a tolerable way to eliminate and add entries into the array, I though maybe it was better to:
- Only read the wanted sections of the original header into the array variable
- Rename the needed entries and in the array
- Write the transformed array to the destination workbook
I have little to no experience in VBA, but such a simple operation as this one seems to be a nightmare.
My try below:
' Initialization
Dim wbkOld As Workbook
Dim wbkNew As Workbook
Set wbkOld = Workbooks.Open(Filename:="filepath", ReadOnly:=True)
Set wbkNew = Workbooks.Add
wbkNew.SaveAs Filename:="filename"
' STEP 1: Only read wanted sections of the original header
' I know the size of the target headers row beforehand
Dim strHeadersArr(1 To 6) As String
' Now the problem:
' The following statement would work if I wanted to load the entire headers row...
strHeadersArr = wbkOld.Sheets(1).UsedRange.Rows(1).Value
'... but I want to load only a subsection
' (e.g. the first 4 headers/cells and then the last 2 headers/cells, dropping the 5 headers/cells in between)
_unknown code here_
' STEP 2: Rename the needed entries
strHeaderArr(2) = "newColumnName"
' STEP 3: Write down
wkbNew.Sheets(1).Range("A1").Value = strHeaderArr
Also be appreciated if you proposed a different/better way to accomplish what I'm looking for.