How to switch between workbooks - vba

I have problem with switching between workbooks. Could you take a look at code and say what is wrong with attitude to problem which i am trying? Or propose some other way to do this.
Sub copy_spreadsheets()
Dim wb As Workbook, wb_main As Workbook, path As String, sheet_name As String, x As Integer, i As Integer, source_sheet As Worksheet, ws As Worksheet
path = "C:\Users\me\Desktop\folder\"
Set wb_main = ThisWorkbook
For x = 2 To 10
i = 2
sheet_name = ("sheet" & i & ".xlsx")
Set wb = Workbooks.Open(path & sheet_name)
Set sourceSheet = Worksheets("sheet1")
sourceSheet.Activate
sourceSheet.Cells.Select
Selection.Copy
Workbooks("C:\Users\me\Desktop\folder\sheet1.xls").Worksheets("Sheet1").Activate
Set ws = Sheets.Add
i = i + 1
Next x
End Sub

There is a Workbook.Activate method as well as Worksheet. Try activating the workbook before activating sheets within that workbook.

Related

VBA Debug code for using a partial name match to copy and paste between active/open workbooks

I found this code in another thread here but can't get it working in my book...
What I'm trying to achieve is... The macro to be called from a wb called "SHIFT REPORT*" which looks for and switches to a wb called "PlayerTransactionReport*" to copy some data before switching back to the SHIFT REPORT and pasting it in.
The code I have is:
Sub Import_Data()
Dim wb As Workbook
Dim ShiftReport As Workbook
Dim PlayerTransactionReport As Workbook
Set ShiftReport = ThisWorkbook
For Each wb In Workbooks
If Left(wb.Name, 23) = "PlayerTransactionReport" Then Set PlayerTransactionReport = wb
Next
Sheets("Sheet1").Select
Columns("A:Z").Select
Selection.Copy
Set PlayerTransactionReport = ThisWorkbook
For Each wb In Workbooks
If Left(wb.Name, 10) = "ShiftReport" Then Set ShiftReport = wb
Next
Sheets("Data").Select
Range("A1").Select
ActiveSheet.Paste
End Sub
Currently, it's not setting the PlayerTransactionReport to the active wb but throughout the process of debugging this by myself I've had various degrees of success, but I fear that this one might have between me, Please Help!
Thanks, Stuart
You have to refer to the Parent Worksheet, whenever you are refering to Sheets() and Columns():
Sub Import_Data()
Dim wb As Workbook
Dim ShiftReport As Workbook
Dim PlayerTransactionReport As Workbook
Set ShiftReport = ThisWorkbook
For Each wb In Workbooks
If Left(wb.Name, 23) = "PlayerTransactionReport" Then Set PlayerTransactionReport = wb
Next
PlayerTransactionReport.Sheets("Sheet1").Select
Columns("A:Z").Select
Selection.Copy
Set PlayerTransactionReport = ThisWorkbook
For Each wb In Workbooks
If Left(wb.Name, 10) = "ShiftReport" Then Set ShiftReport = wb
Next
PlayerTransactionReport.Sheets("Data").Select
Range("A1").Select
ActiveSheet.Paste
End Sub
If you do not refer to the parent worksheet, then the ActiveSheet or the sheet where the code is, is the one referred.
As a next step you can improve the following 2 points:
How to avoid using Select in Excel VBA
Check whether the PlayerTransactionReport is not Nothing, before calling it:
If Not PlayerTransactionReport Is Nothing Then
PlayerTransactionReport.Sheets("Sheet1").Select
Columns("A:Z").Select
Selection.Copy
End If
Stop using Select and Activate.
Sub Import_Data()
Dim w As long
Dim PlayerTransactionReport As Workbook, ShiftReport As Workbook
Set ShiftReport = ThisWorkbook
For w = 1 to Workbooks.count
If Left(Workbooks(w).Name, 23) = "PlayerTransactionReport" Then
Set PlayerTransactionReport = Workbooks(w)
exit for
end if
Next w
if w > Workbooks.count then
debug.print "cannot find PlayerTransactionReport"
exit sub
end if
PlayerTransactionReport.workSheets("Sheet1").Columns("A:Z").Copy _
destination:=ShiftReport.workSheets("Data").Range("A1").
End Sub

copying range end xl down pasting different Wb

I've got a macro recorder code (with select and activate) that I'm trying to simplify. It currently looks like this:
Windows("Stambestand.xlsm").Activate
Range("AA2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Windows("Ijking document.xlsm").Activate
Range("B3").Select
ActiveSheet.Paste
As of recently I've started using variables and want to trim down the code. I'm thinking along these lines:
WbStambestand.WsStam.Range("AA2", Selection, Selection.End(xlDown)).Copy WbIjk.WsIjk.range("A1").paste
Workbooks("WbStambestand").Worksheets("WsStam").Range("AA2", Selection, Selection.End(xlDown)).Copy
However, these don't function. I'm hoping you guys can help me along. Much appreciated.
FYI, these are my variables (they are declared). The Ijk ones are the paste destination.
Dim WbStambestand, WbIjk As Workbook
Dim WsIjk, WsStam As Worksheet
Set WsIjk = ActiveSheet
Set WbIjk = ActiveWorkbook
Set WsIjk = ActiveSheet
Set WbIjk = ActiveWorkbook
Set WbStambestand = Workbooks.Open(stam)
Set WsStam = WbStambestand.Worksheets("stambestand")
Try this
Sub abc()
Dim WbStambestand As Workbook
Dim WbIjk As Workbook
Dim WsIjk As Worksheet
Dim WsStam As Worksheet
Dim LastRow As Long
Dim stam As String
stam = "C:\Users\Admin\Desktop\Stambestand.xlsm" ' path with complete file name with extension.
Set WsIjk = ActiveSheet
Set WbIjk = ThisWorkbook ' workbook which has current code
Set WbStambestand = Workbooks.Open(stam)
Set WsStam = WbStambestand.Worksheets("stambestand")
LastRow = WsStam.Range("AA2").End(xlDown).Row
WsStam.Range("AA2:AA" & LastRow).Copy WsIjk.Range("B3")
End Sub

copy entire data from one workbook to another using vba

I'm getting a "object variable or with block variable not set" error message when running the following code. What is wrong with the code?
Dim directory As String, fileName As String, sheet As Worksheet, i As Integer, j As Integer
Dim mainworkBook As Workbook
Application.ScreenUpdating = False
directory = "C:\Users\425410\Desktop\MYExcel\"
fileName = Dir(directory & "*.xl??")
Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Set x = Workbooks.Open(directory & fileName)
Windows("Book3.xlsm").Activate
Set ws1 = x.Sheets(1)
Set ws2 = y.Sheets(1)
With ws1
.Cells.Copy ws2.Cells
y.Close True
x.Close False
End With
As #user3514930 commented you need to set y to a workbook object.
Added some extra code edits.
'<<I think grouping similar types together when declaring variables is clearer than OP
'<<Also I prefer all declarations at the start of subroutines
Dim directory As String, fileName As String
Dim sheet As Worksheet
Dim i As Integer, j As Integer
Dim mainworkBook As Workbook
Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Application.ScreenUpdating = False
directory = "C:\Users\425410\Desktop\MYExcel\"
fileName = Dir(directory & "*.xl??")
Set x = Workbooks.Open(directory & fileName)
Windows("Book3.xlsm").Activate
Set y = Workbooks("someopenBook") '<<<<<<<<<<<<<
Set ws1 = x.Sheets(1)
Set ws2 = y.Sheets(1)
'<<not sure why you have the workbook close lines within the With block
With ws1
.Cells.Copy ws2.Cells
End With
y.Close True
x.Close False

Copy Worksheet from one workbook to another. Type Mismatch 13

I'm looking to copy just one worksheet from a workbook to another and then change the name. Nothing hugely fancy.
I keep getting a type-mismatch error and I don't know why. I've used code from others which they say works but just doesn't for me.
Any ideas.
Private Sub cmdStockLog_Click()
week = ThisWorkbook.Sheets("Stock Sheet").Range("F1")
Dim wb As Workbook
Set wb = Workbooks.Open(ThisWorkbook.Path & "\Data\FOH Stock.xlsx")
ThisWorkbook.Sheets("Stock Sheet").Copy After:=Workbooks(wb).Sheets(Worksheets.Count)
ActiveSheet.Name = "WK" & week
End Sub
Try this code:
Private Sub cmdStockLog_Click()
Dim wb As Workbook
Dim ws As Worksheet
Dim week
week = ThisWorkbook.Sheets("Stock Sheet").Range("F1")
Set wb = Workbooks.Open(ThisWorkbook.Path & "\Data\FOH Stock.xlsx")
ThisWorkbook.Sheets("Stock Sheet").Copy After:=wb.Sheets(wb.Sheets.Count)
Set ws = wb.Sheets(wb.Sheets.Count) ' new sheet
ws.Name = "WK" & week
End Sub

getting error "Object Variable or With block variable not set"

I have created an Add-In for Excel which determines the name of ActiveSheet and ActiveWorkbook. The code I used is below. When I run the Add-In it is showing the above mentioned error after the message box "variables set". But when I run it in macros it is working fine. I don't understand what is happening with the Add-In. Could anyone help me with this?
Sub sheetvalues()
Dim bk As Workbook, sht1 As Worksheet, sht2 As Worksheet, sht3 As Worksheet
Dim book As String, sht As String, i As Integer, j As Integer
Dim att(1 To 4) As String, att_col(1 To 4) As Integer
MsgBox ("variables set")
book = ActiveWorkbook.Name
sht = ActiveSheet.Name
MsgBox ("names set")
Set bk = Workbooks.Add
With bk
.Title = "MissingValues"
.SaveAs Filename:="MissingValues.xls"
End With
Set sht1 = bk.Sheets.Add
sht1.Name = "EndOne"
Set sht2 = bk.Sheets.Add
sht2.Name = "EndTwo"
Set sht3 = bk.Sheets.Add
sht3.Name = "EndThree"
MsgBox (book & " " & sht)
MsgBox ("completed")
End Sub
A common issue that causes this issue is forgetting to use 'Set' with assigning a value to a variable.
Check if the workbook in Excel is asking you if you want to open a write-protected version or not. I think while this question is present the workbook is not considered Active, nor is any other
Like #TimWilliams said, you will get this error if your add-in is the only workbook loaded. In that case there is no active workbook and your code is failing on the line
book = ActiveWorkbook.Name
You can check for the existence of a workbook by adding the following lines:
Set bk = Application.ActiveWorkbook
If bk Is Nothing Then
MsgBox ("No workbook open. Creating a new one.")
Set bk = Workbooks.Add(xlWBATWorksheet)
Set sht1 = bk.ActiveSheet
End If
So you end up with:
Sub sheetvalues()
Dim bk As Workbook, sht1 As Worksheet, sht2 As Worksheet, sht3 As Worksheet
Dim book As String, sht As String, i As Integer, j As Integer
Dim att(1 To 4) As String, att_col(1 To 4) As Integer
MsgBox ("variables set")
Set bk = Application.ActiveWorkbook
If bk Is Nothing Then
MsgBox ("No workbook open. Creating a new one.")
Set bk = Workbooks.Add(xlWBATWorksheet)
Set sht1 = bk.ActiveSheet
End If
book = ActiveWorkbook.Name
sht = ActiveSheet.Name
MsgBox ("names set")
Set bk = Workbooks.Add
With bk
.Title = "MissingValues"
.SaveAs Filename:="MissingValues.xls"
End With
Set sht1 = bk.Sheets.Add
sht1.Name = "EndOne"
Set sht2 = bk.Sheets.Add
sht2.Name = "EndTwo"
Set sht3 = bk.Sheets.Add
sht3.Name = "EndThree"
MsgBox (book & " " & sht)
MsgBox ("completed")
End Sub