I am working on a Excel VBA script that requires me to copy and paste different details from the original excel workbook into 5 new excel workbooks in an orderly manner. Also, I am adding the Macros into a Add-in so that it can be added into another computer. My only problem is that I am unable to reference the original workbook because:
1) The original workbook's file name will always be changing, therefore I am unable to pull out the workbook based on its name/assign the workbook name to a variable.
2) Excel VBA have ActiveWorkbook/ThisWorkbook property but it does not ActiveWorkbook Property will always be changing, depending on the current workbook that is active. That being said, ActiveWorkbook will not work for me as the creation of new workbooks will overwrite the original workbook. ThisWorkbook property does not work for me because the VBA codes will be stored in an Add-in, but I want to save the new files in the original workbook's location instead (This is when I use ThisWorkbook.Path to identify the location).
Does anyone know if I can make Excel VBA read the original file's location and lock that value into a variable such that I can always call it back again when I need to reference it again?
Below is a sample code that I have. Any help will be greatly appreciated. Thank you!
Option Explicit
Sub new()
Dim createWb As Workbook
Dim Originalwks As Worksheet
Dim createWbName As String
Set Originalwks = ActiveWorkbook.ActiveSheet
createWbName = Left(ActiveWorkbook.Name, Len(ActiveWorkbook.Name) - 4)
Set createWb = Workbooks.Add
createWb.SaveAs Filename:=ThisWorkbook.Path & Application.PathSeparator & createWbName
createWb.Sheets("Sheet1").Name = createWbName
Originalwks.UsedRange.Copy
createWb.Worksheets(createWbName).Range("A1").PasteSpecial xlValues
'I will still be adding new workbooks by copying values from the original workbook.
'But how do I pull out the original workbook again?
createWb.Close SaveChanges:=True
End Sub
Originalwks
is theActivesheet
inActiveWorkbook
, then can't you just doDim OriginalWb as Workbook
andSet OriginalWb = ActiveWorkbook
? – BigBenOriginalWb
- reference that. Although theActiveWorkbook
will change, that variable will always refer to the same workbook - the first one that was active.OriginalWks
works the same way - you have a reference to the first active sheet even ifActiveSheet
is changing. – BigBenThisWorkbook
is always referring to the workbook that's running the VBA code. If that's an Excel add-in, thenThisWorkbook
is the hidden workbook for that Excel add-in. – Mathieu Guindon