Trying to Copy Workbook data but when Source opens nothing happens - excel

I'm using the following code:
Dim sourceBook As Workbook
Dim targetBook As Workbook
'## Open both workbooks first:
Set targetBook = Application.ActiveWorkbook
Set sourceBook = Application.Workbooks.Open("...\Documents\Log.xlsm")
'
With sourceBook.Sheets("Sheet1").UsedRange
'Now, paste to y worksheet:
targetBook.Sheets("Sheet1").Range("A1").Resize( _
.Rows.Count, .Columns.Count) = .Value
End With
'Close
sourceBook.Close
But when i run it my source book opens and nothing happens after. Not sure what i'm missing. Both workbooks have the same extension xlsm. Ive tried to change the source to xlsx also but Same result
Edit: Ive replaced the with statement with the following:
targetBook.Sheets("Sheet1").Range("A1").Value = sourceBook.Sheets("Sheet1").Range("A1")
to at least see if i can copy 1 value but when the sourcebook is opened it stops there.

I have recreated your example, and think it is do with the way you are opening the document. In your open method you have three dots Open("...\documents")
It raised an error for me, so can you check that is what you meant? It worked if I used ..\ rather than ...\

Related

Workbook.close causes sub to exit

I have a set of versioned Excel documents that I am trying to get to auto-update when there is a new version available. What fails is that the .close method is not just closing one of the workbooks but also exiting the sub.
The process:
The sub gets called from Worksheet_Activate and immediately checks to see if an upgrade is needed. If needed, it collects all of the names of the sheets (except the "Count" sheet which is a copy from a template), creates a new workbook with the same sheets as the old one, copies the data over to the proper sheets, closes the old workbook, deletes the old workbook, saves the new workbook with the same name as the old workbook.
Pretty straight forward and it worked great until it didn't. I'm not sure why, but now when the wkbFrom.Close command is executed it also exits the procedure.
I've been digging around and the only answer I could find that seemed to address my issue was to give some delay before/after the close so that Excel will have time to finish and not collide with itself. So I tried putting in a 5 second delay before the close command but to no avail.
Excel doesn't crash, it's still up and running properly. I checked the Event Viewer and Excel is not throwing any errors. The sub simply closes the workbook and then exits the sub.
Here is the full code for the sub.
Sub UpgradeHWWorkbook(Optional HWSheetVersion As Double)
'--------------------------------
'This sub upgrades a hardware tracking
'workbook to the newest version based on
'version in the variable HWSheetVersion
'--------------------------------
'Before anything else, Check to see if upgrade is needed.
'If sheet version is equal or larger than the plugin version
'OR the name of the sheet is wrong, exit without upgrading
'---------------------------------------------------------------------
If HWSheetVersion >= HWPlugInVersion Or _
Not ActiveSheet.CodeName Like "BaseHWSheet_*" Then
Exit Sub
End If
'---------------------------------------------------------------------
'VAR declarations----------------
Dim wkbFrom As Workbook 'Holds the original workbook
Dim wkbTo As Workbook 'Holds the new workbook
Dim sWKB As Workbook 'Holds Workbook where Count sheet is kept
Dim sWKS As Worksheet 'Holds Count sheet
Dim wks As Worksheet 'Holds worksheets
Dim wksNames() As String 'Holds the names of all the worksheets
Dim wkbFromName As String 'Holds the name of the original workbook
Dim wkbFromPath As String 'Holds the path of the original workbook
Dim wkbToPath As String 'Holds the path where the new workbook will be saved
Dim rng As String 'Holds the range of cells that will be copied
Dim x As Byte 'Holds counter
Dim wksName As Variant 'Holds the name of the current worksheet
'--------------------------------
'Sub Settings--------------------
Set wkbFrom = ActiveWorkbook 'Set the active workbook as the one that the data comes from
wkbFromPath = wkbFrom.Path 'Grabs the path of the original workbook
wkbFromName = wkbFrom.Name 'Grab the original workbook name
wkbToPath = wkbFrom.FullName 'Grab the path path and name in another var so we don't have to do it by hand
ReDim wksNames(0) 'Starts off the array that will hold the worksheet names
x = 0 'Flush the counter
rng = "A2:D18" 'The range of cells that will be copied and pasted
Application.DisplayAlerts = False 'Turn off annoying pop-ups
Set sWKB = Workbooks("StockroomAddins.xlam") 'Workbook with Count sheet to copy to new workbook
Set sWKS = sWKB.Worksheets("Count") 'Count sheet to copy to new workbook
'--------------------------------
'Get all of the worksheet names (except Count) in the workbook
'-----------------------------------------------------------------------
For Each wks In wkbFrom.Worksheets 'itenerate through the book
If Not wks.Name = "Count" Then 'If the worksheet isn't the "Count" sheet...
wksNames(x) = wks.Name 'add the sheet name to the array wksName()
x = 1 + UBound(wksNames) 'Increase the array by 1
ReDim Preserve wksNames(x) 'Increase the size of the array by 1
End If
Next wks
'-----------------------------------------------------------------------
'Create new workbook & add Count sheet
'-----------------------------------------------------------------------
Set wkbTo = Workbooks.Add 'Create the new workbook
wkbTo.Activate 'Make sure new book is active book
sWKS.Copy Before:=Sheets("Sheet1") 'Add the Count sheet to workbook
'-----------------------------------------------------------------------
'Iterate through the sheets in the original workbook, add sheets with the same name to the new book, copy data from the old sheet to the new sheet
'-----------------------------------------------------------------------
For Each wksName In wksNames 'Loop through all of the worksheet names and...
If Not wksName = "" Then 'If it isn't blank...
Call NewHardwareTrackingSheet(wksName, wkbTo) 'Call the sub that creates a new tracking sheet
wkbFrom.Worksheets(wksName).Range(rng).Copy 'Copy the data from the old sheet
wkbTo.Worksheets(wksName).Range(rng).PasteSpecial _
Paste:=xlPasteValues 'Paste the data (Values only) into the new sheet
End If
Next wksName
wkbTo.Worksheets("Sheet1").Delete 'Delete the default "Sheet 1" that every new workbook has
wkbFrom.Close Savechanges:=False 'close the original workbook
'-----------------------------------------------------------------------
'Delete the old workbook and save the new one in the same place with the same name as the old one
'-----------------------------------------------------------------------
Kill wkbToPath 'Kill the original
wkbTo.SaveAs Filename:=wkbToPath, FileFormat:=52 'Save the new as the original
Application.DisplayAlerts = True 'Turn annoying pop-ups back on
'-----------------------------------------------------------------------
'Clean up-------------------------------------
Set wkbFrom = Nothing: Set wkbTo = Nothing: Set sWKB = Nothing
Set wks = Nothing: Set sWKS = Nothing
'---------------------------------------------
End Sub
Any ideas on what I've messed up? I figured that since it worked at one point and now doesn't, that I've probably messed up the code somewhere but I'm not seeing it.
OK, I found my answer and I feel a bit stupid about it. Thanks to the folks who asked me some questions because they caused the thought process that worked.
It seems that the spreadsheet I was using to test the code must have gotten corrupted. I tried it on a couple of other files and it worked correctly. No wonder I couldn't find a code issue: there isn't one.
Goes to show the old adage "Measure twice, cut once." I should have tested on multiple files and not assumed my single test file was right.
Much thanks to those who read, thought about, and commented on my post. It is appreciated.
EDIT: Or not......
Came in this morning and it's not working again. There's got to be something in my code that is causing the issue on some and not on others. TBH, I have no idea what it is.
This is really causing me to bang my head on the wall.
OK, so I think I've figured this out.
I am calling this Sub to check the version each time a sheet is activated with this:
Public Sub Worksheet_Activate()
Application.Run "StockroomBarcodeSheets.UpgradeHWWorkbook", HWSheetVersion
End Sub
To do some other testing, I set up another sub inside my plug-in that just called the UpgradeHWWorkbook sub with a fake HWSheetVersion so I could force a workbook to upgrade. Lo, and behold, this setup worked perfectly every time.
So, when I call from the Worksheet_Activate() it exits on the .close command. When I call it from a sub inside the add-in, it works perfectly.
Because the UpgradeHWWorkbook is in a plug-in I thought that the restriction upon closing the calling workbook wouldn't come into affect. I was wrong.

passing variables from multiple workbooks to one workbook

I am using Visual basic from excel to open a different workbook and pass some things from one to another. I have the second file opening fine however I cant get the second file to read the things I need.
Sub createExcel()
Cells(1, 1).Text = "va02"
Dim objExcel
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open(filepath)
End Sub
this is my code to open the second application. I have 2 variables in 2 cells in the first workbook. How would one go about getting the variables. the problem i have encountered is; the second workbook can be called from any file, in any folder.
i would try
variable = Workbooks(firstWorkbook.xlsm).worksheets(sheet1)...
however the worksheets dont have the same names either. please help
thanks
Your code is in Workbook1, and opens Workbook2. So it's Workbook1 that does everything - so " I cant get the second file to read the things I need" is not meaningful.
Sub Demo(filepath as string)
ThisWorkbook.Worksheets(1).cells(1,1).text = "This is written by initial Workook"
Dim Wb as Workbook
Set Wb = Workbooks.Open(filepath)
Wb.Sheets(1).cells(1,2) = "So is this, even though it's in a different workbook"
End Sub

Calling an opened workbook in VBA

this is what i currently have,
Dim mastertemp As Workbook
Dim testproject As Workbook
Set testproject = Workbooks("C:\Users\zzz\Documents\Test Project.xlsm")
Set mastertemp = Workbooks("C:\Users\zzz\Documents\MasterTemp.xlsx")
mastersheet.sheets("Sheet1").activate
the third line of code is giving me subscript out of range, any ideas?
I want to be able to jump between workbooks without the system giving me "workbook is already open, reopening would discard all changes etc"
I would do something like this:
Dim wbk as Workbook
Set wbk = Workbooks("Test Project.xlsm")
do stuff
Workbooks.Open ("C:\Users\zzz\Documents\MasterTemp.xlsx")
do stuff
wbk.Sheets("Dashboard").Activate
If you will always know the name of your workbook you can do
workbooks("Test Project").sheets("Dashboard").Activate 'add the file extension to the name if you've turned on file extensions in windows explorer
If the workbook name might be changing (or evening if it isn't, and you'll be referring to the workbook multiple times) then findwindow's suggestion is the way to go.
dim TestWorkbook as workbook
set TestWorkbook=Workbooks.Open ("C:\Users\zzz\Documents\Test Project.xlsm")
TestWorkbook.sheets("Dashboard").activate
I hope this helps.
If you know the workbook is already open, then refer to it by name in the Workbooks collection:
Dim testProject as Workbook
Set testProject = Workbooks("C:\Users\zzz\Documents\Test Project.xlsm")
testProject.Sheets("Dashboard").Activate
If you don't know whether the workbook is open, then you can use some error-handling logic, like:
Dim testProject as Workbook
On Error Resume Next
' Attempt to index this workbook from the open Workbooks collection:
Set testProject = Workbooks("C:\Users\zzz\Documents\Test Project.xlsm")
If Err.Number <> 0 Then
' If the above fails, then the workbook isn't open, so we need to open it:
Set testProject = Workbooks.Open("C:\Users\zzz\Documents\Test Project.xlsm")
End If
On Error GoTo 0

VBA subscript out of range, code 9

I'm conducting my very first VBA macro and I'm having some difficulties with this seemingly easy code to read data from a closed workbook into my currently opened one.
Sub KAuto()
Dim path As String
path = "C:\files\Utfall.xlsx"
Dim currentWb As Workbook
Set currentWb = ThisWorkbook
Dim openWb As Workbook
Set openWb = Workbooks.Open(path)
Dim openWs As Worksheet
Set openWs = openWb.Sheets("March")
currentWb.Sheets("Indata").Range("A1").Value = openWs.Range("A3").Value
End Sub
The problem I'm having is that I get a code 9, subscript out of range. But I've checked that A1 and A3 is existent for the current workbook and the imported one respectively.
What I have tried to do is to omit the ".Value" in all combinations, as that was what the original author did.
Googling this problem I've encountered that people misused functions which I do not use, for instance windows(), or omitted "" for referencing the worksheets, or simply misspelled things. I don't Think I have any of these, and so I need further help.
How can I correct my subscript out of range? Is there a better way to achieve this copying of cells? In the future I want to import 10 files, will this then be obsolete? (I recall someone posting something in the lines of openWb = [file1,file2,file3] and looping through them, but I cannot find it; does anyone have a link?
EDIT: I've copied the path to the file from its properties, so it ought to be correct.
EDIT2:
currentWb.Sheets("Indata").Range("A1").Value = openWs.Range("A3").Value
snippet gives the error
EDIT3: VB editor print screen:
Try using ActiveWorkbook instead of ThisWorkbook.
Set currentWb = ActiveWorkbook
ThisWorkbook refers to the workbook in which the code resides. ActiveWorkbook refers to the workbook that is currently active i.e. "on top" in the Excel application. It looks like your case, the code resides in a different workbook; so what you want is ActiveWorkbook.
And you can ommit the .value from last line.
currentWb.Sheets("Indata").Range("A1") = openWs.Range("A3")
Your code worked fine for me, that`s why I cannot be sure if it will help. There can be an issue, when opening the openWs. The error line can be evaluated before the openWs is actually open. Then maybe add a line :
Application.Wait (Now + TimeValue("00:00:03")) 'this is 3 seconds from now
after the Set openWb = Workbooks.Open(path).

run time error 1004 in opening two different workbooks

I am trying to open two different workbooks for transferring data. The complete location of workbooks are in two cells of the current workbook. First workbook opens correctly but there is error in opening other workbook. It says:
run time error 1004. File can't be found.
However, if i use path of workbook directly in the code, then it works fine. Anybody please tell me what I am doing wrong.
Sub ProcessReport()
Dim MainWb As Workbook
Dim DestWb As Workbook
' Load source and destination files
Set DestWb = Workbooks.Open(Range("E10").Value)
Set MainWb = Workbooks.Open(Range("E6").Value)
' Code for manipulation
End Sub
In your original code the second workbooks.open command is reading the cell "E6" from the workbook "DestWb" because that is the activeWorkbook at the time that command is executed, rather than the workbook where the macro is saved.
You can fix this by changing:
Set DestWb = Workbooks.Open(Range("E10").Value)
Set MainWb = Workbooks.Open(Range("E6").Value)
To this:
Set Ws = ThisWorkbook.Sheets("Sheet1")
Set DestWb = Workbooks.Open(Ws.Range("E10").Value)
Set MainWb = Workbooks.Open(Ws.Range("E6").Value)
This will save "Sheet1" from the workbook where the macro is running as an object reference so that your macro tries to use the filepaths in "E10" and "E16" from the workbook where the macro is saved. Range("E6").Value is now qualified with the worksheet ws.
You can change "Sheet1" to whatever the tab is where the filepaths are in your macro workbook.

Resources