I'm trying to figure this out. In my main sub, I call a function. Somehow it ended my run at the end of that function. It displays "Before end" and never displays "I made it out" Does anybody know what the problem is?
Sub Main()
call CopyAndDelete()
msgbox "I made it out"
End Sub
Function CopyAndDelete()
Dim CopyFromWB As Workbook
Dim CopyToWB As Workbook
Dim wb As Workbook
Dim CopyThisWS As Worksheet
Dim ws As Worksheet
Dim Path As String
Dim FileName As String
Application.DisplayAlerts = False
Set CopyToWB = Workbooks("test.xlsm")
CopyToWB.Activate
For Each ws In ActiveWorkbook.Sheets
Select Case ws.Name
Case "A"
ws.Delete
Case "B"
ws.Delete
Case "C"
ws.Delete
Case "D"
ws.Delete
End Select
Next ws
Path = Application.GetOpenFilename(Title:="choose a file")
FileName = Right(Path, Len(Path) - InStrRev(Path, "\"))
For Each wb In Workbooks
If wb.Name = FileName Then
Workbooks(FileName).Close
End If
Next wb
Set CopyFromWB = Workbooks.Open(Path)
Set CopyThisWS = CopyFromWB.Worksheets(1)
CopyThisWS.Copy After:=CopyToWB.Worksheets(1)
ActiveSheet.Name = "New A"
CopyFromWB.Close
Application.DisplayAlerts = True
MsgBox "Before end"
End Function
This works:
Sub Main()
Call CopyAndDelete
MsgBox "I made it out"
End Sub
Function CopyAndDelete()
MsgBox "Before end"
End Function
So perhaps you are closing the worksheet you were in when you called the macro? The Macro should be added to a Module and maybe it needs to be in a Module in the Normal template with the function declared as public:
Sub Main()
Call CopyAndDelete
MsgBox "I made it out"
End Sub
Public Function CopyAndDelete()
... your rest of the code ...
MsgBox "Before end"
End Function
Hth,
Related
I am able to rename the activesheet using the following code but need to combine this with (first) duplicating the original sheet:
Sub CopySheet()
Dim strName As String
strName = InputBox("Budget2")
If strName = "" Then
Beep
Exit Sub
End If
ActiveSheet.Copy
ActiveSheet.Name = strName
End Sub
Per the documentation for the Worksheet.Copy method, using it without specifying either the Before or After argument will create a new Workbook, containing only that Worksheet.
So, to add a copy of the ActiveSheet after the ActiveSheet in the same Workbook, you can just change ActiveSheet.Copy to ActiveSheet.Copy After:=ActiveSheet
Make sure you check if the new sheet name already exists.
Make sure you keep track of where the copied sheet appears eg. after the source sheet SourceSheet.Copy After:=SourceSheet so you can pick up it's index which is 1 after the source sheet's: Set NewSheet = ThisWorkbook.Sheets(SourceSheet.Index + 1).
Finally make sure to catch errors on renaming if user entered not allowed characters or too long sheet names.
So you would end up with something like:
Option Explicit
Public Sub CopySheet()
Dim InputName As String
InputName = Application.InputBox("Budget2", Type:=2) '2 = text: https://learn.microsoft.com/en-us/office/vba/api/excel.application.inputbox#remarks
' user pressed cancel or entered nothing
If (VarType(InputName) = vbBoolean And InputName = False) Or InputName = vbNullString Then
Beep
Exit Sub
End If
' check if new sheet name already exists
On Error Resume Next
Dim TmpWs As Object
Set TmpWs = ThisWorkbook.Sheets(InputName)
On Error GoTo 0
If Not TmpWs Is Nothing Then
MsgBox "The Sheet '" & InputName & "' already exists", vbCritical
Exit Sub
End If
Dim SourceSheet As Object
Set SourceSheet = ActiveSheet
SourceSheet.Copy After:=SourceSheet
Dim NewSheet As Object
Set NewSheet = ThisWorkbook.Sheets(SourceSheet.Index + 1)
On Error GoTo ERR_RENAME
NewSheet.Name = "InputName"
On Error GoTo 0
Exit Sub
ERR_RENAME:
MsgBox "Sheet could not be renamed.", vbCritical
Err.Clear
End Sub
Hi there My VBA code does not want to close my Raw data File properly.
I have a data capture form then , When I hit Submit, Opens another Excel File, Copies all the data into it and is supposed to save and close the workbook.
My code is as follows:
Private Sub submit_Click()
'Open Workbook
If MsgBox("You are about to Submit, Are you sure?" & vbCr & "Please make sure that the OUTCOME box is complete", vbYesNo) = vbNo Then Exit Sub
Dim wb As Workbook, sh As Worksheet
Set wkb = Workbooks.Open("\\ServerName\Reports Folder\Team Name\Manager Name\RAW\RAW QC data.xlsx")
'Make Daily_Tracking_Dataset active
'Determine emptyRow
'Transfer Information
Set wb = Workbooks("RAW QC data.xlsx")
Set sh = wb.Sheets(1)
cAry = Array(Me.QCBX, Me.CallBX, Me.INBX, Me.AgntBX, Me.VoxBX, Me.ClntBX, Me.PolBX, Me.DateBX1, Me.AuditBX1, Me.TextBox7, Me.TextBox8, Me.OUTBX1, Me.Cbx1_1, Me.Cbx1_2, Me.Cbx1_3, Me.Cbx1_4, Me.OUTBX2, Me.Cbx2_1, Me.Cbx2_2, Me.Cbx2_3, Me.OUTBX3, Me.Cbx3_1, Me.Cbx3_2, Me.OUTBX4, Me.Cbx4_1, Me.Cbx4_2, Me.Cbx4_3, Me.OUTBX5, Me.Cbx5_1, Me.Cbx5_2, Me.Cbx5_3, Me.Cbx5_4, Me.Cbx5_5, Me.Cbx5_6, Me.Cbx5_7, Me.Cbx5_8, Me.ACBX, Me.QTBX, Me.QFBX)
With sh
For i = 1 To 39
.Cells(Rows.Count, i).End(xlUp)(2) = cAry(i - 1).Value
Next
End With
'Save the Raw data
wb.Close SaveChanges:=True
End Sub
What is happening is that it looks like it is working but when I try to submit the next one, It gives me the SAVE AS window
You have both wkb and wb in your code. Probably this is not what you intend. Just try changing wkb to wb in your code. That's a good reason to start using Option Explicit - What do Option Strict and Option Explicit do?
In general, something as simple as this should be working:
Public Sub TestMe()
'Dim wb As Workbook
Dim wkb As Workbook
Dim sh As Worksheet
Set wkb = Workbooks.Open(ThisWorkbook.Path & "\Testing.xlsx")
'Set wb = Workbooks("Testing.xlsx")
'Put your loop instead of the TEST later:
wb.Worksheets(1).Cells(1, 1) = "TEST"
Application.DisplayAlerts = False
wkb.Save
Application.DisplayAlerts = True
wkb.Close
End Sub
I am a new user of vba.
There is recently a vba problem that has left me rather clueless and helpless - subscript out of range - on a particular user's computer when every other user seems to have no issue with using the macro (myself included) hence I can't simply trial and error to troubleshoot.
Hence really need expert help from all of you! Really really appreciated!!
I have used a series of vba, which will run one after another and have pasted them in chronological order as follows.
VBA 1
Sub VBA_1()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Outline.ShowLevels 1, 1
Next ws
End Sub
VBA 2
Sub VBA_2()
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
ws.Protect ("Password")
Next ws
End Sub
VBA 3
Sub VBA_3()
Dim iRet As Integer
Dim strPrompt As String
'Prompt
strPrompt = "This will take about 2 minutes. Click 'OK' to proceed."
'Show msgbox
iRet = MsgBox(strPrompt, vbOKCancel)
'When user clicked 'OK'..
If iRet = vbOK Then
'SaveAs Function
Dim fName As String
fName = Application.GetSaveAsFilename(, "Excel Binary Workbook (*.xlsb), *.xlsb")
If fName = "False" Then
MsgBox "File not saved.", vbOKOnly
Cancel = True
End If
Application.EnableEvents = False
ThisWorkbook.SaveAs Filename:=fName, FileFormat:=xlExcel12
Application.EnableEvents = True
' Calculate
Application.Calculate
Application.ScreenUpdating = True
' Outlet
Worksheets("Total Outlets").Activate
'Copy and Paste this portion to each worksheet
For Each cell In Range("A1")
If cell.Value = "Not Applicable" Then
ActiveSheet.Visible = xlSheetHidden
Else
Call HypMenuVRefresh
End If
Next
'End Outlet & Copy and Paste
Worksheets("D11101").Activate
For Each cell In Range("A1")
If cell.Value = "Not Applicable" Then
ActiveSheet.Visible = xlSheetHidden
Else
Call HypMenuVRefresh
End If
Next
Worksheets("D11102").Activate
For Each cell In Range("A1")
If cell.Value = "Not Applicable" Then
ActiveSheet.Visible = xlSheetHidden
Else
Call HypMenuVRefresh
End If
Next
'Hide sheets accordingly
Worksheets("Restaurant List").Visible = xlSheetVeryHidden
Worksheets("Hotel List").Visible = xlSheetVeryHidden
'Recalculate
Application.Calculate
Application.ScreenUpdating = True
'Renaming of tabs
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
If ws.Range("A2").Value = 1 Then
If ws.Visible = xlSheetVisible Then
On Error Resume Next
ws.Name = ws.Range("A10").Value
End If
End If
Next ws
'Save Workbook
ActiveWorkbook.Save
'Enable finishing screen to be 'Input'
Sheets("Input").Select
'Show msgbox
MsgBox ("Retrieval Completed!")
Else
MsgBox ("Retrieval of Data Cancelled")
End If
End Sub
I can think of the following possible causes but do not say any of them is the actual cause:
"...on a particular user's computer..."
Then:
the version of Excel/VBA is different;
somehwere a global Option Base is set (but I believe this cannot be set global, i.e. applicable to all workbooks loaded);
somewhere a separator is "hard coded" that does not conform to the Windows global setings (Control Panel --> Region and Language --> Formats --> Additional Settings);
the language differs with a reflection in VBA (e.g. a keyword/function name in the native language or identifier names with non-US ASCII 7 bit characters).
To find in where the program encounters the error (and stops), make a function that writes a status message to a file after every major step. Make sure to close the file after every message so the message is actually written.
I have the below code where the user is promted to select a workbook, I want to ensure that the user is selecting a specific file, and to do this I want to verify upon opening the workbook that the Sheet names are matching what I am expecting them to be:
Private Sub CommandButton1_Click()
Dim wb1 As Workbook, wb2 As Workbook
Dim Ret1
Set wb1 = ActiveWorkbook
Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
, "Please a file to load from")
If Ret1 = False Then Exit Sub
Set wb2 = Workbooks.Open(Ret1)
If wb2.Sheet1.Name = "Sum" And wb2.Sheet2.Name = "Names" And wb2.Sheet3.Name = "Things" Then
MsgBox "Fine"
'Code Here
Else
MsgBox "Issue"
'Code Here
End If
wb2.Close SaveChanges:=False
Set wb2 = Nothing
Set wb1 = Nothing
End Sub
Unfortunately when I run the above code I get an "Object doesn't support this property or method error." on the line If wb2.Sheet1.Name = "Sum" And wb2.Sheet2.Name = "Names" And wb2.Sheet3.Name = "Things"
Help please!
You can use this function to check whether sheet exist or not:
Function IsSheetExist(wb As Workbook, shName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = wb.Worksheets(shName)
On Error GoTo 0
IsSheetExist = Not ws Is Nothing
End Function
and use it like this:
If IsSheetExist(wb2, "Sum") And IsSheetExist(wb2, "Names") And IsSheetExist(wb2, "Things") Then
MsgBox "Fine"
'Code Here
Else
MsgBox "Issue"
'Code Here
End If
if you want to check whether thouse sheets exist in workbook in specific order, you can use this approach:
Function IsContainsSheetsInOrder(wb As Workbook) As Boolean
IsContainsSheetsInOrder = False
If wb.Sheets.Count < 3 Then Exit Function
If wb.Sheets(1).Name <> "Sum" Then Exit Function
If wb.Sheets(2).Name <> "Names" Then Exit Function
If wb.Sheets(3).Name <> "Things" Then Exit Function
IsContainsSheetsInOrder = True
End Function
and then:
If IsContainsSheetsInOrder(wb2) Then
MsgBox "Fine"
'Code Here
Else
MsgBox "Issue"
'Code Here
End If
Or, sticking closer to his original script, change wb1.sheet#.Name to wb1.sheets(#).Name like this:
If wb2.Sheets(1).Name = "Sum" And wb2.Sheets(2).Name = "Names" And wb2.Sheets(3).Name = "Things" Then
I was wondering if it is possible to check for a particular sheets for its availability. If it is around, it will continue on with the rest of the code. If not around then it will add in the sheet.
I have thought of it but it is giving me error. Do share some info if u know something! thanks!
sub macro1()
If sheets("Test") = False Then
Sheets.Add.Name = "Test"
End If
'Run my code
End Sub
Like this?
Sub Sample()
Dim ws As Worksheet
On Error Resume Next
Set ws = Sheets("Test")
On Error GoTo 0
If ws Is Nothing Then
Set ws = Sheets.Add
ws.Name = "Test"
End If
'~~> Run your code
End Sub
Another approach ... create a function that
- accepts a workbook object and the name of the sheet you're after and
- returns tru if the sheet is found in the workbook
Function SheetExists(oWorkbook As Workbook, sSheetname As String)
Dim oWs As Worksheet
For Each oWs In oWorkbook.Worksheets
If oWs.Name = sSheetname Then
SheetExists = True
Exit Function
End If
Next
End Function
Sub TestSheetExists()
If SheetExists(ActiveWorkbook, "Bob") Then
MsgBox "Found it"
Else
MsgBox "No joy"
End If
End Sub