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
Related
I can run this VBA script from the current workbook, but I want to run from another new workbook and get the result on it.
Sub ListAllSheets()
Dim ws As Worksheet
Dim Counter As Integer
Counter = 0
For Each ws In ActiveWorkbook.Worksheets
ActiveCell.Offset(Counter, 0).Value = ws.Name
Counter = Counter + 1
Next ws
End Sub
It depends a bit on if the workbook is open already, and ActiveCell works only when the sheet is Active so if you HAVE TO use ActiveCell
Sub ListAllSheets()
Dim wb As Workbook
Set wb = Workbooks("Transactions")
Dim ws As Worksheet
Dim Counter As Integer
Counter = 0
For Each ws In wb.Worksheets
ws.Activate
Application.ActiveCell.Offset(Counter, 0).Value = ws.Name
Counter = Counter + 1
Next ws
End Sub
This may not do exactly what you want, as neither your question nor your code example were very clear (to me). Try to find another way that does not use ActiveCell at all for better results. Maybe something like this:
Sub ListAllSheets()
Dim wb1 As Workbook
Set wb1 = Workbooks("Transactions")
Dim ws1 As Worksheet
Dim wb2 As Workbook
Set wb2 = Workbooks("OtherWorkbook")
Dim ws2 as Worksheet
Set ws2 = wb2.Worksheets("Sheet1")
Dim Counter As Integer
Counter = 1
For Each ws1 In wb1.Worksheets
ws2.Cells(Counter, 1).Value = ws1.Name
Counter = Counter + 1
Next
End Sub
A more reliable way to set a Workbook object is to grab when you open it:
Set wb1 = Workbooks.Open("C:\Transactions.xlsx")
Assume there is a workbook with seven sheets, and the sheet names are as follows:
"Terms"
"Revolvers"
"15"
"22"
"55"
"59"
"146"
I need VBA code that will identify the highest numbered sheet name of any sheet in the whole workbook. In this example, it should identify 146 as the highest number. Then the code should create a new sheet, with a sheet name that is one integer higher than the previous sheet name. In this example, the new sheet would be created and then named "147". Below is my code, I just need to replace "tab name + 1" with the proper function:
Sub AddSheet()
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim strName As String: strName = "tab name + 1"
Dim ws As Worksheet
Set ws = wb.Worksheets.Add(Type:=xlWorksheet)
With ws
.Name = strName
End With
End Sub
Edit Based on BigBen's Answer Below
Sub AddSheet()
Dim wb As Workbook: Set wb = ActiveWorkbook
Dim strName As String: strName = CStr(MaxSheetNumber(wb) + 1)
Dim ws As Worksheet
Set ws = wb.Worksheets.Add(Type:=xlWorksheet)
With ws
.Name = strName
End With
End Sub
Function MaxSheetNumber(ByVal wb As Workbook) As Long
Dim ws As Worksheet
For Each ws In wb.Worksheets
Dim i As Long
If IsNumeric(ws.Name) Then
If CLng(ws.Name) > i Then
i = CLng(ws.Name)
End If
End If
Next
MaxSheetNumber = i
End Function
Perhaps a function like this:
Function MaxSheetNumber(ByVal wb As Workbook) As Long
Dim ws As Worksheet
For Each ws In wb.Worksheets
Dim i As Long
If IsNumeric(ws.Name) Then
If CLng(ws.Name) > i Then
i = CLng(ws.Name)
End If
End If
Next
MaxSheetNumber = i
End Function
This can be easily modified to return a default value, say 1, if no numbered sheets exist in the workbook (although it will currently return 0 and that might be what you want, if you plan to add 1 for the new tab).
In your code:
strName = CStr(MaxSheetNumber(wb) + 1)
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
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
I am looking for a script that will copy a specific range of data, across multiple worksheets, and then paste that data into a brand new Workbook. With my basic knowledge I can do this for a single worksheet in the workbook, but not multiple.
Example, copy cells A7:S1000 from Wkst A and then cells A7:S1000 from Wkst B.
Then paste those cells in a new workbook, on two new worksheets Wkst A and B.
I do not want to save the new workbook, and it must be a brand new workbook that is created each time.
Any suggestions?
Here is an option, you would just pass your range to the DuplicateToNewWB procedure:
Public Function WorksheetExists(wbSource As Workbook, strWorksheet As String) As Boolean
Dim intIndex As Integer
On Error GoTo eHandle
intIndex = Worksheets(strWorksheet).Index
WorksheetExists = True
Exit Function
eHandle:
WorksheetExists = False
End Function
Public Sub DuplicateToNewWB(rngSource As Range)
Dim wbTarget As Workbook 'The new workbook
Dim rngItem As Range 'Used to loop the passed source range
Dim wsSource As Worksheet 'The source worksheet in existing workbook to read
Dim wsTarget As Worksheet 'The worksheet in the new workbook to write
Set wbTarget = Workbooks.Add
For Each rngItem In rngSource
'Assign the source worksheet to that of the current range being copied
Set wsSource = rngItem.Parent
'Assign the target worksheet
If WorksheetExists(wbSource:=wbTarget, strWorksheet:=wsSource.Name) Then
Set wsTarget = wbTarget.Worksheets(wsSource.Name)
Else
Set wsTarget = wbTarget.Worksheets.Add
wsTarget.Name = wsSource.Name
End If
'Copy the value
wsTarget.Range(rngItem.Address) = rngItem
Next
'Cleanup
Set rngItem = Nothing
Set wsSource = Nothing
Set wsTarget = Nothing
Set wbTarget = Nothing
End Sub