Excel 2016: VBA code in one workbookwill affect cells in other workbooks - vba

I've used the same code in Excel 2013 and Excel 2010, it works perfectly fine, but when the system upgraded to Excel 2016, things changed, code works in one book will be implemented in other workbook if I type words in that workbook, any idea? thanks a lot
here is the part of the code
```
Sub createsheets()
On Error Resume Next
Dim sh As Worksheet
Dim ws As Worksheet
Application.DisplayAlerts = False
For Each ws In Workbooks("Book2").Worksheets
If ws.Name <> "test" Then ws.Delete
Next
For j = 4 To 10
PauseTime = 5
starter = Timer
Do While (Timer < starter + PauseTime)
Application.StatusBar = "do nothing..."
DoEvents
Loop
Application.StatusBar = ""
Workbooks("Book2").Worksheets.Add.Name = "name" & j - 3
current_worksheet_name = "name" & j - 3
Workbooks("Book2").Worksheets(current_worksheet_name).Cells(1, 1) = "this is a test"
Next
End Sub
```
***for this code, if i type words in another workbook, say the workbook name is "ABC", new sheets with name "namej" will be created in my current workbook"ABC".
which is apparently unacceptable, I think i've specified the workbook , but it still doesn't work

You may try something like this...
Sub createsheets()
Dim wb As Workbook
Dim sh As Worksheet
Dim ws As Worksheet
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wb = Workbooks("Book2.xlsx")
If Not wb Is Nothing Then
On Error Resume Next
For Each ws In wb.Worksheets
If LCase(ws.Name) <> "test" Then ws.Delete
Next
For j = 1 To 7
wb.Sheets.Add(after:=Sheets(Sheets.Count)).Name = "name" & j
Set sh = ActiveSheet
sh.Cells(1, 1) = "this is a test"
Next
Else
MsgBox "Book2.xlsx is not opened.", vbExclamation
End If
Application.ScreenUpdating = True
End Sub

Related

Display all available sheets in combobox, except the hidden ones, (loop through sheets add to list) VBA

Okay genius hive mind, what am I doing wrong this time?
'wb and ws dimmed in module level declarations...
Set wb = ThisWorkbook
wb.activate
Dim I As Integer, sheetCount As Integer
sheetCount = wb.Worksheets.Count
Dim sheetNum As Integer
sheetNum = 1
With cboCopyFromSheet 'combobox
For I = 0 To sheetCount - 1
'not sure why the capital 'I' describing an object?
'copied from MS documentation
If wb.Worksheets(sheetNum).Visible = True Then
.AddItem wb.Worksheets(sheetNum).Name, I '<----Error
End If
sheetNum = sheetNum + 1
Next I
End With
Weirdly this only happens when I = 9 and sheetnum = 10
None of the sheets are currently hidden ( but some will be )
sheet 10 happens to be a blank sheet...
We are very confucius.
Error thrown is "invalid argument"
Any Clues?
A similar approach to Fane's answer, using the For Each statement.
Sub Whatever()
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Visible Then combo.AddItem ws.Name
Next
End Sub
Try the next (simple) code, please. Creating the habit to use combobox List property, will be helpful when you will need to rapidly load a big range (multi-columns, too):
Sub testLoadComboSheetsNames()
Dim sh As Worksheet, arrSh As Variant, k As Long
ReDim arrSh(1 To ThisWorkbook.Worksheets.count)
For Each sh In ThisWorkbook.Worksheets
If sh.Visible = True Then k = k + 1: arrSh(k) = sh.Name
Next
ReDim Preserve arrSh(k)
cboCopyFromSheet.list = arrSh
End Sub
In order to work, your code must look like the next:
Sub testLoadComboShbis()
Dim i As Long, wb As Workbook
Set wb = ThisWorkbook
For i = 1 To wb.Worksheets.count
If wb.Worksheets(i).Visible = True Then
cboCopyFromSheet.AddItem wb.Worksheets(i).Name
End If
Next i
End Sub

Merge Multiple Workbooks that have multiple worksheets using VBA

I keep having this issue of VBA either not having an object for the new sheet I want to merge, or having the subscript out of range issue come up. None of the things I tried ended up working.
Private Sub MergeButton_Click()
Dim filename As Variant
Dim wb As Workbook
Dim s As Sheet1
Dim thisSheet As Sheet1
Dim lastUsedRow As Range
Dim j As Integer
On Error GoTo ErrMsg
Application.ScreenUpdating = False
Set thisSheet = ThisWorkbook.ActiveSheet
MsgBox "Reached method"
'j is for the sheet number which needs to be created in 2,3,5,12,16
For Each Sheet In ActiveWorkbook.Sheets
For i = 0 To FilesListBox.ListCount - 1
filename = FilesListBox.List(i, 0)
'Open the spreadsheet in ReadOnly mode
Set wb = Application.Workbooks.Open(filename, ReadOnly:=True)
'Copy the used range (i.e. cells with data) from the opened spreadsheet
If FirstRowHeadersCheckBox.Value And i > 0 Then 'Only include headers from the first spreadsheet
Dim mr As Integer
mr = wb.ActiveSheet.UsedRange.Rows.Count
wb.ActiveSheet.UsedRange.Offset(3, 0).Resize(mr - 3).Copy
Else
wb.ActiveSheet.UsedRange.Copy
End If
'thisSheet = ThisWorkbook.Worksheets(SheetCurr)
'Paste after the last used cell in the master spreadsheet
If Application.Version < "12.0" Then 'Excel 2007 introduced more rows
Set lastUsedRow = thisSheet.Range("A65536").End(xlUp)
Else
Set lastUsedRow = thisSheet.Range("A1048576").End(xlUp)
End If
'Only offset by 1 if there are current rows with data in them
If thisSheet.UsedRange.Rows.Count > 1 Or Application.CountA(thisSheet.Rows(1)) Then
Set lastUsedRow = lastUsedRow.Offset(1, 0)
End If
lastUsedRow.PasteSpecial
Application.CutCopyMode = False
Next i
This is where I try to add an extra loop that copies the next sheet (which is Sheet12) but it comes up with the Subscript our of range error.
Sheets("Sheet3").Activate
Sheet.Copy After:=ThisWorkbook.Sheets
Next Sheet
It will then move to the next sheet to perform the loop again.
ThisWorkbook.Save
Set wb = Nothing
#If Mac Then
'Do nothing. Closing workbooks fails on Mac for some reason
#Else
'Close the workbooks except this one
Dim file As String
For i = 0 To FilesListBox.ListCount - 1
file = FilesListBox.List(i, 0)
file = Right(file, Len(file) - InStrRev(file, Application.PathSeparator, , 1))
Workbooks(file).Close SaveChanges:=False
Next i
#End If
Application.ScreenUpdating = True
Unload Me
ErrMsg:
If Err.Number <> 0 Then
MsgBox "There was an error. Please try again. [" & Err.Description & "]"
End If
End Sub
Any help an this would be great
Your source code is very confusing and I believe you're stumbling because the ActiveWorkbook and ActiveSheet change each time you open a new workbook. It's also not clear why you're copying/merging the data from each worksheet in every opened workbook and then copying Sheet3. You will help yourself by more clearly defining what and where your data is and how you're moving it around.
As an example (that may not solve your problem, because your problem is not clear), look at the code below to see how you can keep the sources and destinations straight within your loops. Modify this example as much as you need in order to match your exact situation.
Sub Merge()
'--- assumes that each sheet in your destination workbook matches a sheet
' in each of the source workbooks, then copies the data from each source
' sheet and merges/appends that source data to the bottom of each
' destination sheet
Dim destWB As Workbook
Dim srcWB As Workbook
Dim destSH As Worksheet
Dim srcSH As Worksheet
Dim srcRange As Range
Dim i As Long
Application.ScreenUpdating = False
Set destWB = ThisWorkbook
For i = 0 To FileListBox.ListCount - 1
Set srcWB = Workbooks.Open(CStr(FileListBox(i, 0)), ReadOnly:=True)
For Each destSH In destWB.Sheets
Set srcSH = srcWB.Sheets(destSH.Name) 'target the same named worksheet
lastdestrow = destSH.Range("A").End(xlUp)
srcSH.UsedRange.Copy destSH.Range(Cells(lastdestrow, 1))
Next destSH
srcWB.Close
Next i
Application.ScreenUpdating = True
End Sub

Report Split - Excel VBA Doesn't Copy all Rows and runs Indefinetly

I have written the following Excel VBA Macro, its job is to split a report based on CountryCode. It creates a new workbook, copies the relevant rows to a new workbook, saves the workbook by the CountryCode.
The problem I encouter is missing rows and for one worksheet, it continues running on empty rows? - Basically it doesn't stop and copies over empty rows.
Has cell formatting anything to do with it?
There is another Macro that runs only once which creates the workbooks first. It is only run once on the first worksheet, never again.
Sub RUN2_ReportSplitterOptimized()
Application.DisplayAlerts = False
Application.EnableEvents = False
' Current Workbook
Dim cW As Workbook
Dim cWL As String
Dim cWN As String
Set cW = ThisWorkbook
cWL = cW.Path
cWN = cW.Name
' Current Worksheet
Dim cS As Worksheet
Set cS = ActiveSheet
Do Until IsEmpty(ActiveCell)
' Current Active Cell
Dim aC As Range
Set aC = ActiveCell
' Split input string
Dim CC As String
CC = splitCC(aC.Text)
Dim wb As Workbook
Dim ws As Worksheet
On Error Resume Next
Set wb = Workbooks(CC & ".xlsx")
If Err.Number <> 0 Then
Set wb = Workbooks.Open(cWL & "\" & CC & ".xlsx")
' Create the worksheet
Set ws = wb.Sheets.Add
' Copy the row to the worksheet
ws.Rows(1).Value = cS.Rows(1).Value
ws.Rows(2).Value = aC.EntireRow.Value
With ws
.Name = cS.Name
End With
Else
wb.Activate
On Error Resume Next
Set ws = wb.Sheets(cS.Name)
If Err.Number <> 0 Then
Set ws = wb.Sheets.Add
' Copy the row to the worksheet
ws.Rows(1).Value = cS.Rows(1).Value
ws.Rows(2).Value = aC.EntireRow.Value
With ws
.Name = cS.Name
End With
Else
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
ws.Rows(LastRow + 1).Value = aC.EntireRow.Value
End If
End If
wb.Save
cW.Activate
aC.Offset(1, 0).Select
Loop
Dim wbk As Workbook
For Each wbk In Workbooks
If Len(wbk.Name) = 7 Then
wbk.Close
End If
Next
End Sub
Function splitCC(countrycode As String) As String
If Len(countrycode) < 3 Then
splitCC = countrycode
Else
splitCC = Mid(countrycode, InStr(countrycode, "(") + 1, 2)
End If
End Function
Solved it.
I have used filters as recommended by #sous2817
Instead of running couple of hours - it does the entire job within 2 minutes :D
Thanks for your help
Problem has been solved here: Excel VBA AutoFilter adds empty rows

Excel 2013 VBA Sheets.Add doesn't return new sheet?

So my code was working fine, until IT upgraded me to Excel 2013 and the SDI interface. Now it looks like the Sheets.Add function doesn't return the proper worksheet. The template is added to the correct workbook (Template1) but when I use the returned worksheet, it's referencing a sheet from the active workbook, before all the VBA code ran.
Public Function Worksheet_AddTemplate(TargetBook As Excel.Workbook, _
TemplateFile as String) As Excel.Worksheet
Dim ws As Excel.Worksheet
Debug.Print TargetBook.Name 'Output-->Template1
Set ws = TargetBook.Sheets.Add( _
After:=TargetBook.Sheets(TargetBook.Sheets.Count), _
Type:=TemplateFile)
Debug.Print ws.Parent.Name 'Output-->Book1
Set Worksheet_AddTemplate = ws
Set ws = Nothing
End Function
Can someone else verify that this is happening to you with Excel 2013, and that there isn't something that I'm missing here.
Thanks
P.S. I use a similar routine to create the template workbook/first sheet with no issues.
Edit: The Code is being called from an Add-In. Here is how I call the Function, more or less (I've simplified the routines because it would be too long otherwise)
Private Sub ImportDataFile()
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim sUnit As String, sTemplateFile As String
Dim u As Integer, nUnits As Integer
Application.ScreenUpdating = False
Application.EnableEvents = False
' ...Some setup stuff that I wont bother you with
sTemplateFile = Environ("Temp") & "\Template1.xlt"
For u = 0 To nUnits - 1
If wb Is Nothing Then
Set wb = Workbook_NewTemplate(sTemplateFile)
Set ws = wb.Worksheets(1)
Else
Set ws = Worksheet_AddTemplate(wb, sTemplateFile)
End If
ws.range("H6") = sUnit
' More Loops & writing to cells
For i = 0 To g_Data(f).ItemCount - 1
' Blah, blah, blah
Next
Next
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
I've noticed that if I add 2x DoEvents anywhere in between creating the workbook and adding the second sheet it will work as it did before.
Also, if I use this code in the Worksheet_AddTemplate function it seems to work...
Set wb = Application.Workbooks.Add(Template:=TemplateFile)
Set ws = wb.Worksheets(1)
ws.Copy After:=TargetBook.Sheets(TargetBook.Sheets.Count)
Set ws = TargetBook.Sheets(TargetBook.Sheets.Count)

Skip PERSONAL.xlsb workbook while ListWorkbooks

I have a code to List out all the open workbooks, since all my codes are in Personal.xlsb it also get listed, can anyone tell me an If condition to skip the Personal.xlsb from the list.
And also since Personal.xlsb dose not have a "Data_Index" it tends to give an error for that too
Sub ListWorkbooks()
Dim Wb As Workbook
For j = 1 To Workbooks.Count
Sheets("Data_Index").Select
Range("H3").Cells(j, 1) = Workbooks(j).Name
For i = 1 To Workbooks(j).Sheets.Count
Next i
Next j
End Sub
Sub ListWorkbooks()
Dim Wb As Workbook
Dim i As Integer, j As Integer
For j = 1 To Workbooks.Count
If Workbooks(j).Name <> ThisWorkbook.Name Then
Workbooks(j).Sheets("Data_Index").Range("H3").Cells(j, 1) = Workbooks(j).Name
End If
'not sure what you want to do here
For i = 1 To Workbooks(j).Sheets.Count
Next i
Next j
End Sub
Revised Answer
From reading your comments on other answers you need to also identify which of the open workbooks has a worksheet named Data_Index as well, which is why you were getting a subscript out of range (your code assumed that every workbook had a sheet named Data_Index.
This works for me when I test:
Sub ListWorkbooks()
Dim Wb As Workbook, wb2 As Workbook
Dim sht As Worksheet
Dim c As Range
'Identify which (if any) of the open workbooks has sheet Data_Index
'Note if more than one it will pick the last one it finds
On Error Resume Next
For j = 1 To Workbooks.Count
Set sht = Workbooks(j).Sheets("Data_Index")
Next j
On Error GoTo 0
'Check at least one has the required sheet
If sht Is Nothing Then
MsgBox "There is no open workbook with a sheet named Data_Index", vbExclamation
Else
'Set the destination for the first workbook name
Set c = sht.Range("H3")
For j = 1 To Workbooks.Count
If Workbooks(j).Name = "Personal.xlsb" Then GoTo NextWb
c.Value = Workbooks(j).Name
For i = 1 To Workbooks(j).Sheets.Count
' Whatever you want to do cycling sheets
Next i
'Offset to the next row ready for the next name
Set c = c.Offset(1, 0)
NextWb:
Next j
End If
End Sub
You could do this using arrays, but the above will do it for you.