VBA Set Object within If Statement - excel

So, I created a series of formula on a sheet called Extractor in a workbook called "Processor*". The filename of the workbook "Processor*" will usually vary, having other characters to the right of it. My intention is to copy the range covering all formula I created in a sheet named "Extractor" of the workbook "Processor*", and paste to another workbook "INJ*", with a filename also having variable characters to the right, and specifically to the worksheet named "Table". Upon pasting these formula, it will give results of the different cells i need from "INJ*" based on some conditions I already set in my formula. Please, note that the formula works fine when I do the copy and paste myself. Then I want to copy these results to another sheet on the "Processor*". A sheet called "calculation".
Below is the code I wrote, but I can't seem to get the object defined within the IF statement to work outside the statement. I have several of these files to work with, I will really appreciate your help. Thank you!
Dim wb1 As Workbook, wb2 As Workbook, sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet, sh4 As Worksheet, lrow As Long, lrow2 As Long, rng As Range
Dim Ct As Long
For Each WB In Application.Workbooks
wb1 = Null
If WB.Name Like "Processor*" Then
Ct = Ct + 1
WB.Activate
Set wb1 = ActiveWorkbook
Set sh1 = wb1.Sheets("Extractor")
Set sh2 = wb1.Sheets("calculation")
Exit For
End If
Next WB
If Ct = 0 Then MsgBox "File not open"
Dim Ct2 As Long
For Each WB In Application.Workbooks
If WB.Name Like "INJ*" Then
Ct2 = Ct2 + 1
WB.Activate
Set wb2 = ActiveWorkbook
Set sh3 = wb2.Sheets("Manager Report")
Set sh4 = wb2.Sheets("TABLE")
Exit For
End If
Next WB
If Ct2 = 0 Then MsgBox "File not open"
With wb1
sh1.Range("C38:J42").Copy wb2.sh4.Range("C38")
End With
With sh4
.Range("C42:J42").Copy
sh2.Range("A" & lrow2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
End With

Dim wbProc As Workbook, wbInj As Workbook, sh1 As Worksheet
Dim sh2 As Worksheet, sh3 As Worksheet, sh4 As Worksheet
Set wbProc = WorkbookByName("Proc*")
Set wbInj = WorkbookByName("INJ*")
If wbProc is nothing or wbInj is nothing then
msgbox "missing workbook(s)!"
end if
Set sh1 = wbProc.Sheets("Extractor")
Set sh2 = wbProc.Sheets("calculation")
Set sh3 = wbInj.Sheets("Manager Report")
Set sh4 = wbInj.Sheets("TABLE")
sh1.Range("C38:J42").Copy sh4.Range("C38")
sh4.Range("C42:J42").Copy
sh2.Range("A" & lrow2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
'....
'....
Function used above:
'get an open workbook by [partial] name
Function WorkbookByName(nm As String) As Workbook
Dim WB As Workbook
For Each WB In Application.Workbooks
If WB.Name Like nm Then
Set WorkbookByName = WB
Exit Function
End If
Next WB
End Function
EDIT: you need to specify which workbook to look at for the sheet
Function WorksheetByName(wb As Workbook, nm As String) As Worksheet
Dim sh As Worksheet
For Each sh In wb.Worksheets '<<<
If sh.Name Like nm Then
Set WorksheetByName = sh
Exit Function
End If
Next sh
End Function
Then:
Set sh4 = WorksheetByName(wbInj, "TABLE*")

Try this
Dim wb1 As Workbook, wb2 As Workbook
Dim sh1 As Worksheet, sh2 As Worksheet, sh3 As Worksheet, sh4 As Worksheet
Dim lrow As Long, lrow2 As Long, rng As Range
For Each wb In Application.Workbooks
If wb.Name Like "Processor*" Then
Set wb1 = wb
Set sh1 = wb1.Sheets("Extractor")
Set sh2 = wb1.Sheets("calculation")
Exit For
End If
Next wb
If wb1 Is Nothing Then
MsgBox "File not open"
Exit Sub
End If
For Each wb In Application.Workbooks
If wb.Name Like "INJ*" Then
Set wb2 = wb
Set sh3 = wb2.Sheets("Manager Report")
Set sh4 = wb2.Sheets("TABLE")
Exit For
End If
Next wb
If wb2 Is Nothing Then
MsgBox "File not open"
Exit Sub
End If
sh1.Range("C38:J42").Copy sh4.Range("C38")
sh4.Range("C42:J42").Copy
'''''''''sh2.Range("A" & lrow2).PasteSpecial Paste:=xlPasteValuesAndNumberFormats
lrow2 does not have a value!!!

Related

Setting worksheets dynamically in VBA

I have 66 sheets in my document (Sheet1, Sheet2, Sheet3, ...) and I'm trying to access all of them with the following code:
Dim currentSheet As Worksheet
For i = 1 To 66
Set currentSheet = "Sheet" & Cstr(i)
Next i
However, I get the "type mismatch" error. It seems I cannot set a worksheet using a string. How can I make this work?
I would rather say you do it this way:
Sub LoopThroughWorksheets()
Dim wb As Workbook
Dim ws As Worksheet
Dim wsTarget As Worksheet
'You can set the workbook in which the sheets are there here, if not the current workbook
Set wb = ThisWorkbook
'Loop through each sheet in the current workbook
For Each ws In wb.Sheets
'Set the current ws as the target worksheet
Set wsTarget = ws
'You can then pass this wsTarget worksheet object to other function/sub
'Next worksheet
Next ws
End Sub
Another alternate way:
Sub LoopThroughWorksheetsMethod2()
Dim wb As Workbook
Dim intWs As Integer
Dim wsTarget As Worksheet
'You can set the workbook in which the sheets are there here, if not the current workbook
Set wb = ThisWorkbook
'Loop through all the sheets in the current workbook
For intWs = 1 To wb.Sheets.Count
'Set the current ws as the target worksheet
Set wsTarget = wb.Sheets(intWs)
'You can then pass this wsTarget worksheet object to other function/sub
'Next worksheet count
Next intWs
End Sub
By this you'll be creating a dynamic solution, in case your worksheet count changes in future.
You can retrieve the worksheet as a dynamic array.
Sub test()
Dim vWs() As Worksheet
Dim Ws As Worksheet
Dim n As Integer
For Each Ws In Worksheets
n = n + 1
ReDim Preserve vWs(1 To n)
Set vWs(n) = Ws
Debug.Print vWs(n).Name
Next Ws
End Sub
You can access the worksheet via the Workbook's worksheets collection.
Dim currentSheet As Worksheet
For i = 1 To 66
Set currentSheet = ThisWorkbook.Worksheets("Sheet" i)
'// do stuff with currentSheet...
Next i
Important things here are that this assumes your sheets bear the default names "Sheet" followed by a sequential number. If the loop arrives at "Sheet 33" and it doesn't exist, you will get an error.
If you want to cycle through ALL sheets, you could do it more safely like this:
Dim currentSheet As Worksheet
Dim wsName as String
For Each currentSheet in ThisWorkbook.Worksheets
'// do stuff with currentSheet... for example...
wsName = currentSheet.Name
Next i

VBA: Copy & Paste data from source workbook to destination worksheet If their Cell "A1" value is equal to each others

-I have 2 workbooks now, one is the source, another one is the destination.
-They have the same format, but only the source file contains data
-Both workbooks have the same TABs (But the Tabs are variables, For example, Tab A, B, C are created this time, but next time they might be Tab C, D, E)
I would like to have something like this:
I have already set wb1 (Source) & wb2 (Destination) As those 2 workbooks
Dim ws As worksheet
If wb1.ws.Name = wb2.ws.Name Then
Copy & paste the same Tab info. (Range A1 to last row) from wb1 to wb2
But somehow the code is not supported by VBA. What is the correct code that I can set
Thanks!
Sub Macro1()
' Copy & paste from workbook to workbook
Dim Wb1 As Excel.Workbook
Set Wb1 = Application.Workbooks("Test Template")
Dim Wb2 As Excel.Workbook
Set Wb2 = Application.Workbooks("Hy.xlsm")
Set ws1 = Wb1.Worksheets
Set ws2 = Wb2.Worksheets
If ws1.Name = ws2.Name Then
MsgBox "True"
End If
End Sub
If the tab names are the same, then loop through the worksheets in Wb1 and use each worksheet name to refer to the corresponding worksheet in Wb2, something like this:
Sub Macro1()
Dim Wb1 As Workbook
Set Wb1 = Workbooks("Test Template")
Dim Wb2 As Workbook
Set Wb2 = Workbooks("Hy.xlsm")
Dim ws As Worksheet
For Each ws In Wb1.Worksheets
Dim ws2 As Worksheet
Set ws2 = Nothing
On Error Resume Next
Set ws2 = Wb2.Worksheets(ws.Name)
On Error GoTo 0
If Not ws2 Is Nothing Then
' Do your copy here.
End If
Next
End Sub

Copy from worksheet to worksheet when worksheets names are the same

I have two workbooks with worksheets (having the same names). I would like copy and paste specific cells from one worksheet to another if the name of worksheets are the same.
I tried to compare name of worksheets with array based on names from another workbook but stack when comes to comparison
Sub check()
Dim xArray, i
Dim x As Workbook
Dim ws As Worksheet
Set x = Workbooks.Open("C:\Users\user\Desktop\xxx.xlsx", False)
With x
ReDim xArray(1 To Sheets.Count)
For i = 1 To Sheets.Count
xArray(i) = x.Sheets(i).Name
Debug.Print xArray(i)
Next
End With
x.Close (False)
For Each ws In ThisWorkbook.Worksheets
If ws.Name = xArray Then
' copy for each worksheet define in xArray xxx.xlsx file, range A1,B4,D5:G5
' and paste to worksheet with the same name in this open workbook
End Sub
Thanks for any help !
Use an Error handler to test if the sheet exists.
Sub check()
Dim wb As Workbook, SouceWorksheet As Worksheet, TargetWorksheet As Worksheet
Set wb = Workbooks.Open("C:\Users\user\Desktop\xxx.xlsx", False)
For Each SouceWorksheet In wb.Worksheets
On Error Resume Next
Set TargetWorksheet = ThisWorkbook.Worksheets(SouceWorksheet.Name)
On Error GoTo 0
If Not TargetWorksheet Is Nothing Then
SouceWorksheet.Range("A1").Copy TargetWorksheet.Range("A1")
SouceWorksheet.Range("B4").Copy TargetWorksheet.Range("B4")
SouceWorksheet.Range("D5:G5").Copy TargetWorksheet.Range("D5:G5")
End If
Next
wb.Close False
End Sub
for this functionality , you don't need to create array , it can be done easily with simple logic mentioned below.Also you can customize or replace your workbook and worksheet name and your copy-paste range in the below code.
Sub so()
Dim wb As Workbook
Dim wb1 As Workbook
Set wb = Workbooks("Book1.xlsx")
Set wb1 = Workbooks("Book2.xlsx")
Dim wk As Worksheet
Set wk = wb.Worksheets("Sheet1")
Dim wm As Worksheet
Set wm = wb1.Worksheets("Sheet1")
If (wk.Name = wm.Name) Then
Dim TR As Integer
TR = wk.Range("A" & Rows.Count).End(xlUp).Row
wk.Range("A1:A" & TR).Copy wm.Range("A1")
Application.CutCopyMode = False
End If
End Sub

how to copy data from one sheet to another in different workbooks by sheet name using loops

i want to copy data from worksheets in workbook "Miz" to worksheets in workbook "Prime" by the worksheets names. meaning, i want the data from worksheet "assets" in Miz to be copied to worksheet "assets" in workbook "Prime" by loop (cause i have many worksheets) and so on for other worksheets.
p.s
i got the code to work but it doesn't loop through all the sheets. it only copies the first one and that's it.
Sub WorksheetLoop()
Dim WS_Count As Integer
Dim I As Integer
Dim WsSource As Workbook
Dim WsTarget As Workbook
Dim LastCell As Variant
Set WsSource = Workbooks("Prime.xlsm")
Set WsTarget = Workbooks("Miz.xlsm")
WsTarget.activate
WS_Count = ActiveWorkbook.Worksheets.Count
For I = 1 To WS_Count
If ActiveWorkbook.Worksheets(I).Name = WsSource.Worksheets(I).Name Then
WsTarget.activate
LastCell = Range("A1").SpecialCells(xlCellTypeLastCell).Address
ActiveSheet.Range("A1", LastCell).Select
Selection.Copy
WsSource.activate
ActiveWorkbook.Worksheets(I).activate
Range("F1").Select
Selection.PasteSpecial Paste:=xlPasteAll
End If
Next I
End Sub
This could be done better, but i'm tired. The code loops through each workbook and copies the used range of the source workbook to the destination workbook range F1. Both workbooks must be open, or else you will receive the Subscript out of range error.
Sub WsLoop()
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim WsSource As Workbook
Dim WsTarget As Workbook
Dim Rng As Range
Set WsSource = Workbooks("Miz.xlsm")
Set WsTarget = Workbooks("Prime.xlsm")
For Each ws In WsSource.Sheets
Set Rng = ws.UsedRange
For Each ws1 In WsTarget.Sheets
If ws.Name = ws1.Name Then
Rng.Copy Destination:=ws1.Range("F1")
End If
Next ws1
Next ws
End Sub

Copy/Paste cells & value

I want to copy/paste all worksheet inlcuding the values/formula in the cells to another new workbook.
This code just copy the first ws, but not all other. How can I make sure, that all ws are gettin copied and pasted without writing all the names from the ws in the vba-code?
Sub CopyPaste()
Dim ws As Worksheet, wb As Workbook
Set ws = ActiveSheet
Set wb = Workbooks.Add(xlWBATWorksheet)
ws.Range("A1:G10").Copy
wb.Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteValues
wb.Sheets(1).Range("A1").PasteSpecial Paste:=xlPasteFormats
Application.CutCopyMode = False
End Sub
So i assume you will be saving the second workbook for it to be named? therefore just add your path below where you want to save it, also it now retains the sheet names.
I'm not sure why you are getting a debugger error its working fine for me, try this code and see if you still get it?
Sub newworkbook()
Dim WBN As workbook, WBC As workbook, WB As workbook
Dim WS As String
Dim SHT As Worksheet
Set WBN = Workbooks.Add
For Each WB In Application.Workbooks
If WB.Name <> WBN.Name Then
For Each SHT In WB.Worksheets
SHT.Copy After:=WBN.Sheets(WBN.Worksheets.Count)
WBN.Sheets(WBN.Worksheets.Count).Name = (SHT.Name) & " "
Next SHT
End If
Next WB
Application.DisplayAlerts = False
WBN.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Delete
WBN.Application.DisplayAlerts = True
ActiveWorkbook.SaveAs "C:\YOURPATH\timetable_v2.xls" 'change path to whatever
End Sub
You can try as follow:
Sub CopyPaste()
Dim aSheet As Worksheet
Dim workbook As workbook
Dim index As Integer
Set workbook = Workbooks.Add(xlWBATWorksheet)
For Each aSheet In Worksheets
aSheet.Range("A1:G10").Copy
workbook.Sheets(index).Range("A1").PasteSpecial Paste:=xlPasteFormulasAndNumberFormats
index = index + 1
Application.CutCopyMode = False
Next aSheet
End Sub
Just had a quick look for you, this seems to do the job:
credit: get digital help
Dim WBN As Workbook, WBC As Workbook, WB As Workbook
Dim WS As String
Dim SHT As Worksheet
Set WBN = Workbooks.Add
For Each WB In Application.Workbooks
If WB.Name <> WBN.Name Then
For Each SHT In WB.Worksheets
SHT.Copy After:=WBN.Sheets(WBN.Worksheets.Count)
WBN.Sheets(WBN.Worksheets.Count).Name = Left(WB.Name, 30 - Len(SHT.Name)) & "-" & SHT.Name
Next SHT
End If
Next WB
Application.DisplayAlerts = False
WBN.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Delete
WBN.Application.DisplayAlerts = True
I just deleted WBN.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Delete
And it works fine
The new workbook is saved as an .xlsx file, but of course I Need it as an .xlsm file....when I just added it into the path, it doesnt work
ActiveWorkbook.SaveAs "U:\Excel\timetable_v2.xlsm"

Resources