Calling active VBA script from another workbook - excel

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")

Related

How do I search in another workbook and add to existing number in that other workbook?

With current sheet's (and current workbook) values, I want to search in another workbook, find that value and update the stock (adding the numbers together) which belongs to that value.
My code: (Subscript out of range error)
Sub Upload()
Workbooks.Open "P:\Engineering\Stock Management\EngineerBookingSystem.xlsm"
cProd = Sheet1.Range("D6")
CAdd = Sheet1.Range("F6")
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set wkb = Excel.Workbooks("EngineerBookingSystem.xlsm")
Set wks = wkb.Worksheets("Sheet9")
LastRow = wks.Range(wks.Cells(Rows.Count, 1)).End(xlUp).Row
For i = 2 To LastRow
If wks.Range(wks.Cells(i, 1)) = cProd Then
'found it
wks.Range(wks.Cells(i, 3)) = wks.Range(wks.Cells(i, 3)) + CAdd
End If
Next i
End Sub
I tried YouTube videos, Stack Overflow Q&A, whatever I try errors.
Sub Upload()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
cProd = ws.Range("D6")
CAdd = ws.Range("F6")
Dim wkb As Workbook
Set wkb = Workbooks.Open("P:\Engineering\Stock Management\EngineerBookingSystem.xlsm")
Dim wks As Worksheet
Set wks = wkb.Worksheets("Sheet9")
Dim LastRow As Long: LastRow = wks.Cells(wks.Rows.Count, 1).End(xlUp).Row
For i = 2 To LastRow
If wks.Cells(i, 1) = cProd Then
'found it
wks.Cells(i, 3) = wks.Cells(i, 3) + CAdd
End If
Next i
End Sub

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: Function that will find the sheet name with the highest number of all the sheet names

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)

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

Excel Macro Not Doing anything?

This is my first excel macro (and first time working with VBScript), so it is most likely wrong, but I'm trying to go through each sheet in my workbook, and rename the sheet to the value of the sheets "A2" cell's value. As the name says, the function isn't doing anything when I run it. It is running however. Here is my code:
Sub RenameSheets()
Dim WS_Count As Integer
Dim I As Integer
' Set WS_Count equal to the number of worksheets in the active
' workbook.
WS_Count = ActiveWorkbook.Worksheets.Count
' Begin the loop.
For I = 1 To WS_Count
ActiveSheet.Name = ActiveSheet.Range("A2").Value
Next I
End Sub
Sub RenameSheets()
Dim WS_Count As Integer
Dim I As Integer
WS_Count = ActiveWorkbook.Worksheets.Count
For I = 1 To WS_Count
Dim WS As Worksheet
Set WS = ActiveWorkbook.Worksheets(I)
'Worksheet names can not be null
If Len(WS.Cells(2, 1)) > 0 Then
WS.Name = WS.Cells(2, 1)
End If
Next I
End Sub
You are not selecting the different sheets so ActiveSheet isn't changing. You can rewrite your function below to get the intended result:
Dim currentWorksheet as Worksheet
For Each currentWorksheet in ActiveWorkbook.Worksheets
currentWorksheet.name = currentWorksheet.Range("A2").Value
Next currentWorksheet
what is above is a for..each loop that will set currentWorksheet to each Worksheet in all of the Worksheets in the Workbook.

Resources