Problems with saving excel file after importing data via macro - excel

I want to insert data from source files in my excel model by opening the files and copying and pasting the values. I am just updating the values and not inserting formulas, formats or images etc.
The macro works fine and the inputs are pasted in my excel model. The last command is: ActiveWorkbook.Save
However, sometimes the macro cannot save the file (and I cannot see a regularity here - sometimes it works, sometimes it doesn't) and it displays the error message: "Errors were detected while saving. Microsoft Excel may be able to save the file by removing or repairing some features. To make the repairs in a new file, click continue. To cancel saving the file, click cancel."
Does anyone have an idea on how to fix this error? I am also posting the full code below. Thanks a lot in advance!
' Definitions
Dim i As Integer
Dim mapping_sheet, Worksheet_MVP, Dateiname_Input, Name_Worksheet_Input, Pfad_Input, Pfad_Datei, Zelle, Text As String
' Workbooks
Dim MVP, Auszug As Workbook
Pfad_Input = ActiveSheet.Range("B7").Value
Set MVP = ActiveWorkbook
Sheets("Automatisierung Datenupdate").Activate
Workbooks(MVP.Name).Application.Calculation = xlCalculationManual
Workbooks(MVP.Name).Application.CalculateBeforeSave = False
' 1. Updating Macro
' Copy Pasting Data
If ActiveSheet.Range("E11").Value = "Ja" Then
Dateiname_Input = ActiveSheet.Range("M11").Value
Name_Worksheet_Input = ActiveSheet.Range("D11").Value
Worksheet_MVP = ActiveSheet.Range("B11").Value
Pfad_Datei = Pfad_Input & "\" & Dateiname_Input
Sheets(Worksheet_MVP).Activate
Range("B6:ZZ300").Select
Selection.ClearContents
Set Auszug = Workbooks.Open(Filename:=Pfad_Datei)
Workbooks(Auszug.Name).Activate
Sheets(Name_Worksheet_Input).Activate
Range("A4:ZY298").Select
Selection.Copy
Workbooks(MVP.Name).Activate
Sheets(Worksheet_MVP).Activate
Range("B6").Select
Selection.PasteSpecial Paste:=xlPasteValues
' Close and Save
Workbooks(Auszug.Name).Activate
ActiveSheet.Range("A1").Copy
Workbooks(Auszug.Name).Close savechanges:=False
Workbooks(MVP.Name).Activate
Sheets("Automatisierung Datenupdate").Activate
Range("M11").Select
Selection.Copy
Range("C11").Select
Selection.PasteSpecial Paste:=xlPasteValues
End If
' Save
Sheets("Automatisierung Datenupdate").Activate
Application.ScreenUpdating = True
ActiveWorkbook.Save
End Sub

You mix up the concepts in your code which probably leads to the unexpected/irregular errors.
If you don't specify a data type (or object type) when you dim, the variable is Variant by default. e.g. "Dim MVP" is the same as "Dim MVP as variant"
You do assign your workbooks/worksheets to a variable but don't use the magic. Once set you can just refer to the workbook by referencing the varName.
Although variables are very powerfull, when you just want to use cell values it's better to store these in memory (e.g. an array)
Hereunder an alternative approach, only using the named workbooks/worksheets and minimising the interactions with the sheet by using arrays:
Sub ceci()
'dim vars to specific datatype
Dim wb As Workbook, sh As Worksheet, arr
Set wb = ThisWorkbook
Set sh = wb.Sheets("Automatisierung Datenupdate")
'To minimize the interactions with the sheet we store the data in memory, an array
'here we can access each cell by referencing our array(<rowCounter>, <columnCounter>
'e.g. arr(j,i) => if j = 1 and i = 1 we'll have the values of Cell A1
'we can dump these values anywhere in the activesheet, other sheet, other workbook, ..
Dim sh2 As Worksheet, wb2 As Workbook
arr = sh.Range("A1").CurrentRegion.Value2 'assuming you have data as of A1 we store all in the array, you can fine tune if needed though
If arr(11, 5) = "ja" Then 'E11
'source wb
Set sh2 = wb.Sheets(arr(11, 2)) 'b11
sh2.Range("B6:ZZ300").ClearContents
'wb2 - by specifically naming the workbooks and sheets we avoid unexpected errors
Dim sh3 As Worksheet, arr2, Pfad_Datei As String: Pfad_Datei = wb.Path & "\" & arr(11, 13) 'arr(7, 2) & "\" & arr(11, 13) 'b7 & m11
Set wb2 = Workbooks.Open(Filename:=Pfad_Datei)
Set sh3 = wb2.Sheets(arr(11, 4)) 'd11
arr2 = sh3.Range("A4:ZY298").Value2
sh2.Range(sh2.Cells(6, 2), sh2.Cells(UBound(arr2), UBound(arr2, 2))).Value2 = arr2 'dumb to sheet
'wb1
sh.Range("c11").Value = arr(11, 13) 'm11
End If
wb.Save
End Sub

Related

Copy non adjacent data cells into one workbook

this is the code that i am currently using right now, but its not enough to meet my objectives and i am stuck on how to continue....
So this code will copy the specified data from many other excel workbook in the form of xlsx into a main excel workbook and before that it will scan through the folder which contains all the different data files and the main file(all files supposed to be transfered here in a table form) e.g. Test3.xlsx,Test4.xlsx,Test.xlxs and Main.xlsm in the folder of ScanFiles. so everytime a new files comes into the folder, it will automatically update the main workbook by opening the data workbooks then copy the required data and paste it on the main workbook upon clicking a button.
Sub ScanFiles()
Dim myFile As String, path As String
Dim erow As Long, col As Long
path = "c:\Scanfiles\"
myFile = Dir(path & "*.xlsx")
Application.ScreenUpdating = False
Do While myFile <> ""
Workbooks.Open (path & myFile)
Windows(myFile).Activate
Set copyrange = Sheets("sheet1").Range("A18,B18,C18,D18,A19,B19,C19,D19")
Windows("master-wbk.xlsm").Activate
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
col = 1
For Each cel In copyrange
cel.Copy
Cells(erow, col).PasteSpecial xlPasteValues
col = col + 1
Next
Windows(myFile).Close savechanges:=False
myFile = Dir()
Loop
Range("A:E").EntireColumn.AutoFit
Application.ScreenUpdating = True
End Sub
Objectives: 1st:orignal type of file is in "file" not xlsx, so hope to find a way to open the file in xlsx format automatically before start of copying data.
2nd: requires 3 types of specified data e.g. name,surname(both of them are in fixed position always in A18 to D18 and A19 to D19 , 3rd one is to find the date, however the date is almost always in different positions in the data sheet, so i hope to add on a part to the code that makes it search for something like "ended 20190808" it will always start with ended but will always be in diff rows or even columns. i also need to arrange the data according to the date from newest(top) to oldest(bottom) and state the month of the date in words instead of numbers e.g. june
Deeply Appreciate any form of help but if possible the small section of code that can add on to my coding will make it a lot easier because im tasked to do this in a very limited amount of time
Thank you!!!
Here's some code that does similar things to what you describe. The animated .gif shows it working by stepping through the code. First the 2 data (.xlsx) files are shown so you have an idea of their content. Each is located in the same folder as the main workbook and has data in column A. Then as we step through the code each file is opened, its data manipulated (row 3 is deleted) and transferred into adjacent columns of the main workbook. The code is not limited to .xlsx files and will work with text files as well, as long as ext is defined.
Hopefully, once you understand how this works you can modify it to apply it to your case.
Option Explicit
Sub CombineFiles()
Dim theDir As String, numFiles As Integer
Dim sh As Worksheet, wk As Workbook, newSheet As Worksheet
Dim newColumn As Range, r As Range, s As String
Const ext = ".xlsx"
Err.Clear
theDir = ThisWorkbook.Path
Set newSheet = ThisWorkbook.Sheets.Add
newSheet.Name = "Combined"
Set newColumn = newSheet.Range("A1")
'Loop through all files in directory
s = Dir(theDir & "\*" & ext)
While s <> ""
numFiles = numFiles + 1
On Error Resume Next
Set wk = Workbooks.Open(theDir & "\" & s)
Set sh = ActiveSheet
sh.Rows(3).Delete Shift:=xlUp
Set r = Range("A1")
Range(r, r.End(xlDown)).Copy
newSheet.Activate
newColumn.Offset(0, numFiles) = wk.Name
newColumn.Offset(1, numFiles).Select
newSheet.Paste
Application.DisplayAlerts = False
wk.Close False
Application.DisplayAlerts = True
s = Dir()
Wend
MsgBox (numFiles & " files were processed.")
End Sub
For copy/paste of pictures see examples on this or this page. To find the last cell containing data in a column see this page; note that one example involves using the .find command. More generally, to learn how to use .find in vba, use the macro recorder and then adjust the resulting code.

Something fundamentally wrong with copy/paste script from other workbook

Sorry if this comes across as flippant but I've spent the last 8 hours smashing my head against a wall with this. No matter what variant I try, this code constantly throws up errors of all degrees. I'm competent and I've taken SO MANY EXAMPLES and NONE OF THEM WORK. I'm beginning to think that theres something wrong with where the code is in my workbook. I've put it in Module1, where I normally keep all code.
The actual problem - copy/paste values from one workbook sheet to another after selecting the file from a popup prompt. That's it. The structure of the table is the same but it will need to be moved 5 rows up on the target sheet.
I've tried so many different types of code, which you can see as commented out when I try to iterate to something different. IT WILL NOT REFERENCE THE OPENED WORKBOOK CORRECTLY. Keeps throwing up errors like I'm trying to access some hidden darknet database instead of a file right next to it......
I've tried so many different approaches but they all end up with different errors. the above code gives me 'Runtime error 13. Type, mismatch.' on the line in the loop that tries to copy the code.
I think it all stems from excel not being able to correctly reference the opened file. even though it should.......................
Sub ImportEstimatorData()
Dim xTargetWb As Workbook 'Consolidator
Dim xSourceWb As Workbook 'Estimator
Set xTargetWb = ActiveWorkbook
Dim xTargetRng As Range 'Target row/column in new sheet, changes row starting
Dim xSourceRng As Range 'Source data from Estimator, Never changes
Dim xSourceSt As Worksheet
Dim xTargetSt As Worksheet
Sheets("CR Data").Activate
Set xTargetSt = ThisWorkbook.Sheets("CR Data")
Dim vFile As Variant
'fileToOpen = Application _
' .GetOpenFilename("Text Files (*.txt), *.txt")
'If fileToOpen <> False Then
' MsgBox "Open " & fileToOpen
'End If
'Dim vFile As Variant
'vFile = Application.GetOpenFilename("Excel-files,*.xlsx", 1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
'If vFile = "" Then Exit Sub
'Set targetworkbook
'Set xSourceWb = Workbooks.Open(vFile)
If Not Application.OperatingSystem Like "*Mac*" Then
' Is Windows.
vFile = Application.GetOpenFilename("Excel-files,*.xlsm", 1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If vFile = "" Then
Exit Sub
End If
Else
Exit Sub
End If
' Is a Mac and will test if running Excel 2011 or higher.
' If Val(Application.Version) > 14 Then
' Set xSourceWb = Select_File_Or_Files_Mac
' End If
' End If
'Workbooks.Open (vFile)
Set xSourceWb = Workbooks.Open(vFile)
'Workbooks(xSourceWb).Open
'Workbooks(xSourceWb).Activate
'Set Sheets for both Source & Target Workbooks
'Set xSourceSt = xSourceWb.Sheets("Output data GPE")
'Set xTargetRng = xTargetSt.Range(Cells(4, 2), Cells(80, 16))
Sheets("Output Sheet GPE").Activate 'Range(Cells(1, 1), Cells(2, 2)).Select
Set xSourceWb = ActiveWorkbook
'xSourceWb.Activate
'Set xSourceRng = xSourceSt.Range(Cells(4, 2), Cells(80, 16))
'xSourceRng.Copy xTargetRng
'Workbooks(xSourceWb).Worksheets("Output Sheet GPE").Range(Cells(8, 2), Cells(84, 16)).Copy Workbooks(xTargetWb).Worksheets("CR Data").Range(Cells(4, 2), Cells(80, 16))
For i = 8 To 84
For j = 2 To 16
Workbooks(xSourceWb).Worksheets("Output Sheet GPE").Cells(i, j) = Workbooks(xTargetWb).Worksheets("CR Data").Cells(i - 4, j)
'Debug error here
Next j
Next i
'Workbooks(xWb).Worksheets("CR Data").Range(Cells(4, 2), Cells(80, 16)).Copy Workbooks(xTargetWb).Worksheets("C").Range(Cells(4, 2), Cells(80, 16))
'Workbooks(xTargetWb).Worksheets("CR Data").Range(Cells(4, 2), Cells(80, 16)).PasteSpecial Paste:=xlPasteValues
'Workbooks(xTargetWb).Sheets("CR Data").Range(Cells(4, 2), Cells(80, 16)).Value = Workbooks(xSourceWb).Sheets("Output Sheet GPE").Range(Cells(4, 2), Cells(80, 16))
'xSourceWb.Close
'End If
'End With
End Sub'
Thank you BigBen! That was exactly it! I removed the 'workbooks' encloser and it worked :-)
Copy/paste response below for future perusal:
xSourceWb and xTargetWb are Workbook objects already. Don't enclose them in Workbooks. That said, you don't need a loop for this. – BigBen 16 hours ago

Copy columns to new workbook and save as csv

I'm trying to:
Copy data (columns A and B) from one workbook (data.xlsx).
Paste into a new workbook (as values).
Save as CSV with a filename taken from column A in a third workbook (URLs.xlsx).
Process to repeat, taking the same data (which is randomised every time it is pasted) from data.xlsx and pasted into a new CSV - there are 200 rows in URLs.xlsx and so we should end up with 200 files.
I've read lots of topics, here are two I found:
Excel VBA Copy a Range into a New Workbook
https://www.excelcampus.com/vba/copy-paste-another-workbook/
What I've tried
Copying code and replacing the relevant components from various different articles across the web. Some of them work, but when I add the missing bits, I run into errors I don't understand.
Well here is an example avoiding copy pasting in new workbooks:
Expected input like:
Data.xlsx range A1:B200 with RANDBETWEEN() function:
URLs.xlsx range A1:A200 with some URL like so:
Run this code (will take approximately 1 second on my machine, tested with timer):
Dim wbData As Workbook, WBurls As Workbook
Dim CSVFileDir As String, CSVVal As String
Dim A As Long, X As Long, Y As Long, Z As Long
Option Explicit
Sub Transfer2CSV()
Set wbData = Workbooks("data.xlsx") 'Make sure it is open upon running macro
Set WBurls = Workbooks("URLs.xlsx") 'Make sure it is open upon running macro
For X = 1 To 200 'Looping through the 200 rows of WBurls
CSVFileDir = "C:\YourDrive\" & WBurls.Sheets(1).Cells(X, 1).Value & ".csv"
CSVVal = ""
A = FreeFile
Open CSVFileDir For Output As #A
With wbData.Sheets(1).Range("A1:B200") ' or whichever range you using here
.Calculate 'Randomize your range again
For Y = 1 To 200 'or however many rows you have in column A and B.
For Z = 1 To 2
CSVVal = CSVVal & .Cells(Y, Z).Value & ","
Next Z
Print #A, Left(CSVVal, Len(CSVVal) - 2)
CSVVal = ""
Next Y
End With
Close #A
Next X
End Sub
Output:
With each file looking like:
This should work. Make sure your data and URLS workbooks are open.
Sub Macro1()
Dim wsData As Worksheet, wsUrl As Worksheet, wbNew as Workbook
Dim CSVDir as String, rngU As Range
Set wsData = Workbooks("data.xlsx").Worksheets(1)
Set wsUrl = Workbooks("URLs.xlsx").Worksheets(1)
Set rngU = wsUrl.Range("A1", wsUrl.Range("A" & wsUrl.Rows.Count).End(xlUp))
CSVDir = "C:\Users\thomas.mcerlean\Desktop\Work\" 'you gave this as your dir
Set wbNew = Workbooks.Add
For Each cell In rngU
wsData.Range("A1", wsData.Range("B" & wsData.Rows.Count).End(xlUp)).Copy Destination:= wbNew.Worksheets(1).Range("A1")
wbNew.SaveAs Filename:= CSVDir & cell.Value & ".csv", FileFormat:=xlCSV
Next cell
wbNew.Close SaveChanges:=False
End Sub

Copying base data sheet along with selected sheets from source workbook to new workbook

I am looking at building a master workbook which receives a monthly dump of data for all Cost Centres which will then populate a large number of worksheets within the workbook, and which then need to be split off and sent out to service heads. A service head will receive a selection of worksheets based on the first 4 characters of the sheet name (although this may change in due course).
eg 1234x, 1234y, 5678a, 5678b will produce two new workbooks named 1234 and 5678 with two sheets in each.
I have cobbled some code from various forum to create a macro that will work through a hard coded array defining the service head 4 character codes and create a series of new workbooks. And which seems to work.
However.. I also need to include the main data dump sheet within the source file (called "data") with the the array of files being copied over so that the links remain with the data sheet being copied over. If I write a line to copy over the data sheet separately, the new workbook still refers back to the source file, which service heads do not have access to.
So main question is: how can I add the "data" tab into the Sheets(CopyNames).Copy code so it is copied over with all the other files in the array at the same to keep the links intact?
Second question is if I decide it is the first two characters of the worksheet define the sheets that relate to a service head, how do I tweak the split/mid line of code - I've trialled around but am getting tied up in knots!
Any other tips to make the code more elegant much appreciated (there may be quite a long list of service head codes and I am sure there is a better way of creating a list for the routine to loop through)
Sub Copy_Sheets()
Dim strNames As String, strWSName As String
Dim arrNames, CopyNames
Dim wbAct As Workbook
Dim i As Long
Dim arrlist As Object
Set arrlist = CreateObject("system.collections.arraylist")
arrlist.Add "1234"
arrlist.Add "5678"
Set wbAct = ActiveWorkbook
For Each Item In arrlist
For i = 1 To Sheets.Count
strNames = strNames & "," & Sheets(i).Name
Next i
arrNames = Split(Mid(strNames, 2), ",")
'strWSName =("1234")
strWSName = Item
Application.ScreenUpdating = False
CopyNames = Filter(arrNames, strWSName, True, vbTextCompare)
If UBound(CopyNames) > -1 Then
Sheets(CopyNames).Copy
ActiveWorkbook.SaveAs Filename:=strWSName & " " & Format(Now, "dd-mmm-yy h-mm-ss")
ActiveWorkbook.Close
wbAct.Activate
Else
MsgBox "No sheets found: " & strWSName
End If
Next Item
Application.ScreenUpdating = True
End Sub
Option Explicit
Sub CopySheets()
With ThisWorkbook
Dim SheetIndex As Long
Dim ValidSheetNames() As String
ReDim ValidSheetNames(1 To .Worksheets.Count)
' Build a 1 dimensional array called ValidSheetNames, which contains every sheet in the master workbook other than DEDICATEDSHEET. '
Dim ws As Worksheet
For Each ws In .Worksheets
If ws.Name <> "DEDICATEDSHEET" Then
SheetIndex = SheetIndex + 1
ValidSheetNames(SheetIndex) = ws.Name
End If
Next ws
ReDim Preserve ValidSheetNames(1 To SheetIndex)
' Read all ServiceCodes into a 1-dimensional array '
Dim ServiceHeadCodes As Variant
ServiceHeadCodes = Application.Transpose(.Worksheets("DEDICATEDSHEET").Range("CCLIST[CC]").Value2)
Dim CodeIndex As Long
' Now loop through each ServiceHeadCode '
For CodeIndex = LBound(ServiceHeadCodes) To UBound(ServiceHeadCodes)
' Put all sheet names which contain the current ServiceHeadCode into an array called SheetsToCopy '
Dim SheetsToCopy() As String
SheetsToCopy = Filter(ValidSheetNames, ServiceHeadCodes(CodeIndex), True, vbTextCompare)
' Check if SheetToCopy now contains any sheet names at all. '
If UBound(SheetsToCopy) > -1 Then
' Add the name of the Data sheet to the end of the array '
ReDim Preserve SheetsToCopy(LBound(SheetsToCopy) To (UBound(SheetsToCopy) + 1))
SheetsToCopy(UBound(SheetsToCopy)) = "Data"
Dim OutputWorkbook As Workbook
Set OutputWorkbook = Application.Workbooks.Add
' Copy all sheets which are in SheetToCopy array to newly created OutputWorkbook '
.Worksheets(SheetsToCopy).Copy OutputWorkbook.Worksheets(1)
' Delete the default Sheet1, which should be at the end as copied sheets were inserted before it. '
' But suppress the Are you sure you want to delete this sheet.. message. '
Application.DisplayAlerts = False
OutputWorkbook.Worksheets(OutputWorkbook.Worksheets.Count).Delete
Application.DisplayAlerts = True
' Re-enable alerts, as we want to see any other dialogue boxes/messages
' Not providing a full directory path below means OutputWorkbook will be saved wherever Thisworkbook is saved.'
OutputWorkbook.SaveAs Filename:=ServiceHeadCodes(CodeIndex) & " " & Format(Now, "dd-mmm-yy h-mm-ss") & ".xlsx", FileFormat:=51
OutputWorkbook.Close
Else
MsgBox "No sheets found: " & ServiceHeadCodes(CodeIndex)
End If
Next CodeIndex
End With
End Sub
Untested and written on mobile, sorry for bad formatting.
This approach proposes that you store all service head codes in a 1-column Excel table on a dedicated sheet that is referred to via Excel table nomenclature (which might be easier than ArrayList.Add for each new service head code).
I assume code is stored in master workbook ('thisworkbook'), which might not be true.
You could modify the serviceheadcodes table directly on the spreadsheet itself, if you later decide that SheetsToCopy will be determined by first 2, 3 or X characters -- or you could modify array itself with left$() function.
Hope it works or gives you some ideas.
Edit: This is my sheet and table layout (which I assume matches yours).
And this is what the code above gives me on my computer.

excel vba: Run-time error '438'

Using code from the spreadsheet guru to loop through files in a folder and perform a set task on them, seems to be working properly. Where I may have made a mistake is the set task portion of the code.
Using Excel 2010.
sourcewb = ActiveWookbook
sourcefn = ActiveWorkbook.Name
masterwb = ThisWorkbook
masterwb.Activate
lr = ActiveSheet.ListObjects("DataTbl").ListRows.Count
If ActiveSheet.ListObjects("DataTbl").DataBodyRange(lr, 1).Value = "" Then
sourcewb.Activate
ActiveSheet.ListObjects("IntermidateTbl").DataBodyRange.Copy
masterwb.Activate
ActiveSheet.ListObjects("DataTbl").DataBodyRange(lr, 1).Select
Selection.Paste
newlr = ActiveSheet.ListObjects("DataTbl").ListRows.Count
Range(ActiveSheet.ListObjects("DataTbl").DataBodyRange(lr, 8), _
ActiveSheet.ListObjects("DataTbl").DataBodyRange(newlr, 8)) = "" & sourcefn & ""
Else
ActiveSheet.ListObjects("DataTbl").ListRows.Add AlwaysInsert:=True
sourcewb.Activate
ActiveSheet.ListObjects("IntermidateTbl").DataBodyRange.Copy
masterwb.Activate
ActiveSheet.ListObjects("DataTbl").DataBodyRange(lr + 1, 1).Select
Selection.Paste
newlr = ActiveSheet.ListObjects("DataTbl").ListRows.Count
Range(ActiveSheet.ListObjects("DataTbl").DataBodyRange(lr + 1, 8), _
ActiveSheet.ListObjects("DataTbl").DataBodyRange(newlr, 8)) = "" & sourcefn & ""
End If
There are more than a few errors, I'll try to help with a few.
You are trying to set sourcewb, which is a Workbook object, so you need to change:
sourcewb = ActiveWookbook
To:
Set sourcewb = ActiveWookbook
(the same goes for Set masterwb = ThisWorkbook).
Next, masterwb.Activate, you don't need to Activate the workbook, and it's also safer to also set reference to the sheet you want, you can also add the With statement, and use something like:
With masterwb.Worksheets("SheetName")
lr = .ListObjects("DataTbl").ListRows.Count ' number of rows in "DataTbl" table
You can also set an Object to your ListObjects.
Dim DataTbl As ListObject
Set DataTbl = masterwb.Worksheets("SheetName").ListObjects("DataTbl")
So later on, you can access it's properties much easier (and "cleaner").
For example:
lr = DataTbl.ListRows.Count ' <-- get the rows count of the table
and:
If DataTbl.DataBodyRange(lr, 1).Value = "" Then
And so on, you have way too many places where you Activate the 2 workbooks, and later use ActiveSheet and Selection.
If you describe better what you are trying to achieve, we can help you achieve it in a more reliable way.

Resources