How to refer to a Excel Worksheet by its VBA Object Name in another Workbook? - vba

I have two Excel Workbooks:
Source.xlsx
Tool.xlsm
Source.xlsx contains a Worksheet with the VBA Object Name shtTests:
Let's assume that in Tool.xlsm I have a variable that contains a reference to the Workbook stored in Source.xlsx:
Dim wkbSource as Workbook
Set wkbSource = GetSourceWorkbook() ' Some function that gives a reference to the workbook
Core Question: How can I reference shtTests within Tool.xlsm by using shtTests' VBA Name?
Or to formulate the question as code... assume you have this code snippet:
Dim wkbSourceShtTests as Worksheet
Set wkbSourceShtTests = GetShtTestsFromWkbSources(wkbSources)
Question: What does GetShtTestsFromWkbSources have to look like?
Note: I do not want to reference it by its Excel Name like you would do using wkbSources.Worksheets("Test Cloning") because people might change its Excel Name some day.

Is this what you are trying?
Sub Sample()
Dim wbThis As Workbook, wbThat As Workbook
Dim wsThat As Worksheet
Dim wsCodeName As String
Set wbThis = ThisWorkbook
Set wbThat = Workbooks("Book4") '<~~ Change this to relevant workbook
wsCodeName = "ShtSheets"
Set wsThat = wbThat.Worksheets(CStr(wbThat.VBProject.VBComponents(wsCodeName).Properties(7)))
Debug.Print wsThat.Name
End Sub
Note: For this to work, you need to enable access to Visual Basic Projects
On the File menu Excel, Click Options|Trust Center|Trust Center Settings|Macro Settings, Check the box "Trust Access to the VBA Project Object Model"

If you wanted a function instead of setting up the trusted access then this would probably work:
Sub example()
Dim wkbSource As Workbook
Set wkbSource = GetSourceWorkbook()
Dim wkbSourceShtTests As Worksheet
Set wkbSourceShtTests = GetShtTestsFromWkbSources(wkbSource, "shtTests")
End Sub
Function GetShtTestsFromWkbSources(wkbk As Workbook, codename As String) As Worksheet
For Each sht In wkbk.Sheets
If sht.codename = codename Then Set GetShtTestsFromWkbSources = sht
Next
End Function

Related

Copying a worksheet to another workbook using VBA

I am trying to copy a worksheet from the workbook that the VBA is in (ThisWorkbook) and past it into another workbook that the user has open (ActiveWorkbook). I have written a function but I cannot get it to work. I have done something similar before and I have searched the internet but I cannot find a solution or why it is failing me. What am I doing wrong?
Function workBooks() As String
aWbkName = ActiveWorkbook.Name
tWbkName = ThisWorkbook.Name
Dim wbk1 As Workbook
Dim wbk2 As Workbook
Set wbk1 = tWbkName
Set wbk2 = aWbkName
wbk1.Sheet2.Copy After:=wbk2.Sheets(7)
End Function
Try this and see if it works. It will copy Sheet2 in ThisWorkbook and paste it after Sheet1 in the ActiveWorkbook
Option Explicit
Public Sub copy_sheet()
Dim source_worksheet As Worksheet
Set source_worksheet = ThisWorkbook.Worksheets("Sheet2")
Dim target_worksheet As Worksheet
Set target_worksheet = ActiveWorkbook.Worksheets("Sheet1")
source_worksheet.Copy After:=target_worksheet
End Sub
you don't need all that variable dimming and assigning:
Sub workBooks()
ThisWorkbook.Sheet2.Copy After:=ActiveWorkbook.Sheets(7)
End Sub

VBA - Pull info from one workbook to another

I'm not the greatest with VBA and haven't touched it in years therefore I resort to tutorials so I hope somebody can help!
In the long run I'm trying to, in the following order:
Open an explorer window in one excel document via a button (Done!)
select an excel doc (Hopefully selected multiple docs in the long run)
pull info from a certain row/column of a sheet though to the original excel book
So far I've scoured/chopped and changed and found the following (Thanks JMax on this site)
Sub test()
Dim wb As Workbook, wb2 As Workbook
Dim ws As Worksheet
Dim vFile As Variant
'Set source workbook
Set wb = ActiveWorkbook
'Open the target workbook
vFile = Application.GetOpenFilename("Excel-files,*.xls", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
'Set targetworkbook
Set wb2 = ActiveWorkbook
'For instance, copy data from a range in the first workbook to another range in the other workbook
wb2.Worksheets("Sheet1").Range("C3:D4").Value = wb.Worksheets("Sheet3").Range("A1:B2").Value
End Sub
To me this looks in order however when It opens the excel doc it comes back with the 'subscript out of range' message.
What Im I missing? The cells and naming seem correct to me :(.
Thanks,
Dave
The error is being thrown because a Worksheet name doesn't exist in on of the Worksheet Collections.
wb2.Worksheets("Sheet1")
Worksheets("Sheet3")

Using VBA to copy a spreadsheet from a secondary workbook into the primary one

I need to take a spreadsheet and compare it with a spreadsheet from another workbook. I know that I can do this using VBA, but I will need to copy a spreadsheet from another workbook so that both spreadsheets will reside within the same workbook and be accessible for comparison. How do I copy a spreadsheet from one workbook into another using VBA?
You don't need to copy the worksheets over to compare them. Simply open both WorkBooks and and set reference to there WorkSheets.
Sub CompareWorkBooks()
Dim wbPending As Workbook
Dim wsPending As Worksheet
Set wbPending = Workbooks("Items Pending")
Set wsPending = wsPending.Worksheet("Items")
Dim wbRecieved As Workbook
Dim wsRecieved As Worksheet
Set wbRecieved = Workbooks("Items Recieved")
Set wsRecieved = Worksheet("Items")
End Sub
If you provide names for Workbooks & WorkSheets and provide column information, we can give you better answers in a shorter period of time. Don't be afraid to post your code either.
If you want a user to select the target workbook and worksheet:
Create a userform
Declare targetWorkbook and tartgetWorksheet at the top of the code module
Add a command button and a combo box
When the button is clicked a file dialog is opened
A reference is now set to the open file
The names of all the worksheets are added to the combo
Changing the combo box value will set the refernce to tartgetWorksheet
Option Explicit
Public targetWorkbook As Workbook
Public tartgetWorksheet As Worksheet
Private Sub CommandButton1_Click()
Dim targetWorkbook As Workbook
Dim ws As Worksheet
Set targetWorkbook = getTargetWorkbook
If targetWorkbook = Nothing Then
MsgBox "Sowmthing went wrong", vbCritical, "Try Again"
Else
For Each ws In targetWorkbook.Worksheets
ComboBox1.AddItem ws.Name
Next
End If
End Function
Function getTargetWorkbook() As Workbook
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = False
.Show
On Error Resume Next
Set getTargetWorkbook = Application.Workbooks.Open(.SelectedItems(1))
On Error GoTo 0
End With
End Function
Private Sub ComboBox1_Change()
Set tartgetWorksheet = targetWorkbook.Worksheets(ComboBox1.Value)
End Sub

VBA Error 'Subscript out of Range'

I am trying to create a copy of a large macro enabled (xlsm) file in xlsx format.
Sub Button1_Click()
Dim wb As Workbook
Set wb = Workbooks.Open("C:\original.xlsm")
Dim mySheetList() As String
ReDim mySheetList(0 To (ThisWorkbook.Sheets.Count) - 1)
Dim a As Integer
a = 0
For Each ws In ActiveWorkbook.Worksheets
mySheetList(a) = ws.Name
a = a + 1
Next ws
'actually save
Worksheets(mySheetList).Copy
ActiveWorkbook.SaveAs Filename:="ORIGINAL_COPY.xlsx" 'default ext
wb.Close
End Sub
I am getting subscript out of range error at following line:
mySheetList(a) = ws.Name
You are sizing the array with ThisWorkbook.Sheets but the loop use ActiveWorkbook.Worksheets. You need the same reference to avoid issues when multiple workbooks are opened.
You're using 4 different references to workbooks:
wb, ThisWorkbook and ActiveWorkbook are not necessarily the same thing. Furthermore, when you use Worksheets without prefixing it with a workbook reference, you're implicitly referencing the Activeworkbook. And, when you use Worksheets.Copy without any arguments, you're implictly creating a new workbook.
Currently, if ThisWorkbook has fewer sheets than original.xlsm, then your array will not be large enough to accommodate indexes larger than the count of sheets in ThisWorkbook. That is what is causing your out of bounds error.
I've adjusted the code. This will open the XLSM, copy the sheets, save the new XLSX workbook, and close the original XLSM, leaving the new XLSX workbook open.
Sub Button1_Click()
Dim wbOriginal As Workbook
Dim wbOutput As Workbook
Set wbOriginal = Workbooks.Open("C:\original.xlsm")
Dim mySheetList() As String
ReDim mySheetList(0 To (wbOriginal.Sheets.Count) - 1)
Dim a As Integer
a = 0
For Each ws In wbOriginal.Worksheets
mySheetList(a) = ws.Name
a = a + 1
Next ws
'Unfortunately, Worksheets.Copy isn't a function, so it doesn't
'return the workbook that it creates, so we have to execute the
'copy, then find the activeworkbook
Worksheets(mySheetList).Copy
Set wbOutput = ActiveWorkbook
'actually save
wbOutput.SaveAs Filename:="ORIGINAL_COPY.xlsx" 'default ext
wbOriginal.Close
End Sub
Why bother with all that looping?
Sub MM()
Dim sourceWB As Excel.Workbook
Set sourceWB = Workbooks.Open("C:\Original.xlsm")
sourceWB.SaveAs "C:\ORIGINAL_COPY.xlsx", FileFormat:=xlOpenXMLWorkook
sourceWB.Close False '// Optional
End Sub
The .SaveAs() method would be far more effective.
As mentioned in other answers, your issue seems to be with wb, ActiveWorkbook and ThisWorkbook being used interchangeably when they are actually different things.
wb is a workbook object that has been set to "C:\original.xlsm". It will always refer to that workbook unless you close the workbook, empty the object, or assign a new object to it.
ActiveWorkbook refers to the workbook that is currently active in Excel's forefront window. (i.e. The workbook you can see on your screen)
ThisWorkbook refers to the workbook in which the currently executing code belongs to. To quickly explain the difference:
Workbook A is the only workbook open, and has some code in to open another workbook (let's call it Workbook B).
At the moment, Workbook A is the ActiveWorkbook.
The code in workbook A starts running, workbook A is now the ActiveWorkbook and ThisWorkbook (because the running codes resides in this workbook)
The code opens Workbook B, which naturally opens in the forefront of Excel. Now Workbook B is the ActiveWorkbook and Workbook A is still the ThisWorkbook
Hopefully that clears it up a bit for you...

EXCEL VBA: Copy Sheet from a workbook to another workbook in different location

I am trying to copy a whole sheet from one Excel file to a sheet in another. Following is the code I wrote which doesn't work. Please suggest changes.
Sub copyallwos()
Dim wkbSource As Workbook
Dim wkbDest As Workbook
Dim shttocopy As Worksheet
Dim wbname As String
Set wkbSource = Workbooks.Open("C:\Users\AV\Documents\New folder\SCADA Wos.xlsm")
Set wkbDest = Workbooks("C:\Users\AV\Documents\New folder\MASTER.xlsm")
'perform copy
Set shttocopy = wkbSource.Sheets("tt")
shttocopy.Copy
wkbDest.Sheets("SCADAWOs").Select
ActiveSheet.Paste
End Sub
Try this under 'perform copy
wkbSource.Sheets("tt").Copy After:=wkbDest.Sheets("SCADAWOs")
You can also insert the sheet before your "SCAD..." sheet, just change After:= to Before:=. Also, if you don't necessarily know a sheet name in the destination workbook, you can use After:=Wkbdest.sheets(sheets.count) which will instert it after the last Worksheet.