I am trying, when a line of information is added to one of my sheets, to automatically add that line to a different sheet in the same workbook.
I found this code and tweaked it a little:
Sub addrow()
Public Sub worksheet_change(ByVal target As Range)
Set sourcebook = ThisWorkbook
Set sourcesheet = sourcebook.Worksheets("sheet1")
Set targetbook = ThisWorkbook
Set targetsheet = targetbook.Worksheets("sheet10")
If sourcesheet.Cells(198, 16).Value = "Auto" Or _
sourcesheet.Cells(198, 16).Value = "Connect" Or _
sourcesheet.Cells(198, 16).Value = "Multiple*" Or _
sourcesheet.Cells(198, 16).Value = "Property" Or _
sourcesheet.Cells(198, 16).Value = "Umbrella" Or _
sourcesheet.Cells(198, 16).Value = "WC" Then
GoTo link
Else
GoTo insertion
End If
insertion: targetsheet.Activate
ActiveSheet.Rows(198).EntireRow.Insert
sourcesheet.Activate
link:
'targetsheet.Cells(194, targetsheet.Range("initial response").Column) = sourcesheet.Cells(198, 16).Value
targetsheet.Cells(194, 16) = sourcesheet.Cells(198, 16).Value
targetsheet.Cells(194, 16) = sourcesheet.Cells(198, 16).Value
End Sub
I get the error message «Compile Error: Expected End Sub» and it highlights that first line of code- Sub addrow(). When I try taking this line out, VBA requires me to create a new macro when I try and run it, which then adds that line back in, and I am back to square one.
pavlusha15 Пользователь Сообщений: 4 |
#1 25.06.2017 22:09:12 Дело в том, что на одном листе создана кнопка и к нему привязан модуль с макросом, я хочу переместить кнопку в форму, но вылазит ошибка «Expected End Sub»
Изменено: pavlusha15 — 25.06.2017 22:44:48 |
||
Hugo Пользователь Сообщений: 23699 |
Где-то в форме недописано окончание макроса. |
pavlusha15 Пользователь Сообщений: 4 |
#3 25.06.2017 22:20:28
Хм, ну где именно? |
||
pavlusha15 Пользователь Сообщений: 4 |
#4 25.06.2017 22:21:23
Когда поставил в кнопку, вот так Изменено: pavlusha15 — 25.06.2017 22:21:41 |
||
Ігор Гончаренко Пользователь Сообщений: 14376 |
#5 25.06.2017 22:23:30 а так:
или
как Вам удобно Изменено: Ігор Гончаренко — 25.06.2017 22:24:03 Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||||
Hugo Пользователь Сообщений: 23699 |
#6 25.06.2017 22:33:32
— хотелось ответить, но так отвечать нельзя
|
||||
pavlusha15 Пользователь Сообщений: 4 |
Я просто новичок в этом, спасибо вам большое! |
Юрий М Модератор Сообщений: 60912 Контакты см. в профиле |
pavlusha15, название темы у Вас никудышное. Предложите новое — модераторы поменяют. |
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
Юрий М, может так сгодится:
|
Юрий М Модератор Сообщений: 60912 Контакты см. в профиле |
|
Ігор Гончаренко Пользователь Сообщений: 14376 |
#11 25.06.2017 22:58:00 в каком-то из модулей количество Sub больше, чем количество End Sub Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
Search code, repositories, users, issues, pull requests…
Provide feedback
Saved searches
Use saved searches to filter your results more quickly
Sign up
-
#1
Please can someone help! I’ve never written a macro before! I’ve got this far but keep getting the same error message and despite reading numerous forums for advice, I can’t see where I’ve gone wrong!
I am trying to create a Purchase Order template that will open with a new sequential number each time and will force a new file name when saved, ideally the name to be the sequential number… If it cooooould, I’d quite like the date to drop in upon opening as well
Please help!!
Code:
Private Sub Workbook_Open()
Sub NextPO()
Range("G4").Value = Range("G4").Value + 1
Range("A16:E32").ClearContents
Range("G3").Value = Date
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Sub SavePOWithNewName()
Dim NewFN As Variant
' Copy PO to a new workbook
ActiveSheet.Copy
NewFN = "Y:\\YS-SBS2011\YSL Purchase Order\YSL-PO" & Range("G4") & Range("G3").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
NextPO
End Sub
Last edited by a moderator:
Back into an answer in Excel
Use Data, What-If Analysis, Goal Seek to find the correct input cell value to reach a desired result
-
#2
Rich (BB code):
Private Sub Workbook_Open()
Sub NextPO()
Range("G4").Value = Range("G4").Value + 1
Range("A16:E32").ClearContents
Range("G3").Value = Date
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Sub SavePOWithNewName()
Dim NewFN As Variant
' Copy PO to a new workbook
ActiveSheet.Copy
NewFN = "Y:\\YS-SBS2011\YSL Purchase Order\YSL-PO" & Range("G4") & Range("G3").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
NextPO
End Sub
you don’t call a sub with the title
NextPO will have to exist in the workbook already to avoid an error
-
#3
Hello Jessica
I think the problem is that you have two sets of Sub for each procedure and only one End Sub
Try commenting out the second one by adding a quoute mark like this before Sub:
‘Sub NextPO()
-
#4
I’m not sure what you mean by this? What should I change? Add? Amend?
-
#5
I’m not sure what you mean by this? What should I change? Add? Amend?
Im saying that you have two separate sub names for each of your procedures, and only one End Sub. When the cumputer goes past the End Sub, it finds that there is no End Sub to match the second sub name, so you get the error «(I) Expected (an) End Sub».
So …. If you tell it to ignore one of the sub names everything will be OK
You can make VBA iignore a line of code by putting a quote mark (‘) at the start of the line.
Rich (BB code):
Private Sub Workbook_Open()
'Sub NextPO() This line will be ignored because of the ' mark
Range("G4").Value = Range("G4").Value + 1
Range("A16:E32").ClearContents
Range("G3").Value = Date
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'Sub SavePOWithNewName() This Line will also be ignored
Dim NewFN As Variant
' Copy PO to a new workbook
ActiveSheet.Copy
NewFN = "Y:\\YS-SBS2011\YSL Purchase Order\YSL-PO" & Range("G4") & Range("G3").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
NextPO
End Sub
Last edited:
-
#6
Sorry Jessica — Im having a bad day
I see your trying to NextPO as part of the Worksheet Change module so we need to keep it. The problem is you can’t start to define NextPO from within another procedure that is incomplete as your doing.
It would need to be defined separately and then used rather that defined in Workbook Open (Done by stating it without the sub qualifier which means its being defined. This arrangement should work without errors:
Code:
Private Sub Workbook_Open()
NxtPO
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
SavePOWithNewName
End Sub
Sub SavePOWithNewName()
Dim NewFN As Variant
' Copy PO to a new workbook
ActiveSheet.Copy
NewFN = "Y:\\YS-SBS2011\YSL Purchase Order\YSL-PO" & Range("G4") & Range("G3").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
NxtPO
End Sub
Sub NxtPO()
Range("G4").Value = Range("G4").Value + 1
Range("A16:E32").ClearContents
Range("G3").Value = Date
End Sub
-
#7
Thank you sooo much for your help!
This code seems to work and is inputting the sequential numbers, yay! It is saving the file correctly on opening too buuuuuut………. its saving the file over and over and over again and I can’t stop it! How can I get into the file to work on the code if it’s constantly resaving and I can’t get it to stay on the original!? And what is it that I need to change in the code to make the resave only happen the one time per opening…
GTO
MrExcel MVP
-
#8
Please can someone help! I’ve never written a macro before! I’ve got this far but keep getting the same error message and despite reading numerous forums for advice, I can’t see where I’ve gone wrong!
I am trying to create a Purchase Order template that will open with a new sequential number each time and will force a new file name when saved, ideally the name to be the sequential number… If it cooooould, I’d quite like the date to drop in upon opening as well
…
Hi Jessica,
Off to the rack shortly, but for any «helper», could you expound a bit on this?
In really plain-English, please tell us what you would like the Template to do?
By utter guessing and most likely off-the-mark, but by example nevertheless:
«I have an Excel Template. Upon creating a new workbook based on this template, I would like….» to happen.
Mark
-
#9
Hi Jessica,
Off to the rack shortly, but for any «helper», could you expound a bit on this?
In really plain-English, please tell us what you would like the Template to do?
By utter guessing and most likely off-the-mark, but by example nevertheless:
«I have an Excel Template. Upon creating a new workbook based on this template, I would like….» to happen.
Mark
Hi Mark,
Thanks so much for coming back to me…
I want to have Purchase Order template that will know what the next available PO number is…
So, I want the excel sheet to open with the next sequential number from when previously opened. I then want it to save with this sequential number as the file name.
So… the first one would be PO001 (in the field G4 in my case) and then auto-saved as ‘YSL-PO001’. The next time its opened, if it could then say PO002 and will auto-save as ‘YSL-PO002’. Ideally this should stop duplications and will make sure that all PO’s are saved…
If I could ask for more, I’d also like it to drop ‘today’s date’ in the G3 box but this isn’t essential…
What do you think? Thanks again in advance,
Jessica
-
#10
Thank you sooo much for your help!
This code seems to work and is inputting the sequential numbers, yay! It is saving the file correctly on opening too buuuuuut………. its saving the file over and over and over again and I can’t stop it! How can I get into the file to work on the code if it’s constantly resaving and I can’t get it to stay on the original!? And what is it that I need to change in the code to make the resave only happen the one time per opening…
Hi Jessica
Im glad we are getting a bit closer, but GTO is right that without a clear picture of the objective, we can only try to get your code executing without error, but it could be doing the wrong thing!
Lets look at what we have in the code (post #6)
1. You have a WorkbookOpen Sub, which will execute whenever the workbook containing it is opened. This adds 1 to the value in cell G4, puts the date in G3 and clears cells A16-E32 (Active Worksheet) {sub NxtPO}
2. You also have a WorksheetChange module, which I assume is attached to the active worksheet containng your Counter in G4, and there is the problem. This routine saves the ActiveWorksheet with a new name and increments
your counter , changing the activesheet, which runs the module again.
To resolve, you can either put the counter in a different worksheet, or amend the worksheet change routine to ignore a change to cell G4.
Just one more point: You do appreciate that a new workbook will be saved for every single change to the worksheet that has the change module ?
Last edited:
pavlusha15 Пользователь Сообщений: 4 |
#1 25.06.2017 22:09:12 Дело в том, что на одном листе создана кнопка и к нему привязан модуль с макросом, я хочу переместить кнопку в форму, но вылазит ошибка «Expected End Sub»
Изменено: pavlusha15 — 25.06.2017 22:44:48 |
||
Hugo Пользователь Сообщений: 23244 |
Где-то в форме недописано окончание макроса. |
pavlusha15 Пользователь Сообщений: 4 |
#3 25.06.2017 22:20:28
Хм, ну где именно? |
||
pavlusha15 Пользователь Сообщений: 4 |
#4 25.06.2017 22:21:23
Когда поставил в кнопку, вот так Изменено: pavlusha15 — 25.06.2017 22:21:41 |
||
Ігор Гончаренко Пользователь Сообщений: 13746 |
#5 25.06.2017 22:23:30 а так:
или
как Вам удобно Изменено: Ігор Гончаренко — 25.06.2017 22:24:03 Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
||||
Hugo Пользователь Сообщений: 23244 |
#6 25.06.2017 22:33:32
— хотелось ответить, но так отвечать нельзя
|
||||
pavlusha15 Пользователь Сообщений: 4 |
Я просто новичок в этом, спасибо вам большое! |
Юрий М Модератор Сообщений: 60564 Контакты см. в профиле |
pavlusha15, название темы у Вас никудышное. Предложите новое — модераторы поменяют. |
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
Юрий М, может так сгодится: <#0> |
Юрий М Модератор Сообщений: 60564 Контакты см. в профиле |
|
Ігор Гончаренко Пользователь Сообщений: 13746 |
#11 25.06.2017 22:58:00 в каком-то из модулей количество Sub больше, чем количество End Sub Программисты — это люди, решающие проблемы, о существовании которых Вы не подозревали, методами, которых Вы не понимаете! |
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Expected End Sub |
vblr6.chm1011142 |
vblr6.chm1011142 |
office |
cac2b471-cd7e-7c71-e671-71b9d55b8bd9 |
06/08/2017 |
medium |
An Endprocedure statement must match the procedure in which it occurs. This error has the following cause and solution:
- You used End Function or End Property to end a Sub procedure. Use End Sub for this type of procedure.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
-
#1
Please can someone help! I’ve never written a macro before! I’ve got this far but keep getting the same error message and despite reading numerous forums for advice, I can’t see where I’ve gone wrong!
I am trying to create a Purchase Order template that will open with a new sequential number each time and will force a new file name when saved, ideally the name to be the sequential number… If it cooooould, I’d quite like the date to drop in upon opening as well
Please help!!
Code:
Private Sub Workbook_Open()
Sub NextPO()
Range("G4").Value = Range("G4").Value + 1
Range("A16:E32").ClearContents
Range("G3").Value = Date
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Sub SavePOWithNewName()
Dim NewFN As Variant
' Copy PO to a new workbook
ActiveSheet.Copy
NewFN = "Y:\YS-SBS2011YSL Purchase OrderYSL-PO" & Range("G4") & Range("G3").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
NextPO
End Sub
Last edited by a moderator: Oct 14, 2014
Why does 9 mean SUM in SUBTOTAL?
It is because Sum is the 9th alphabetically in Average, Count, CountA, Max, Min, Product, StDev.S, StDev.P, Sum, VAR.S, VAR.P.
-
#2
Rich (BB code):
Private Sub Workbook_Open()
Sub NextPO()
Range("G4").Value = Range("G4").Value + 1
Range("A16:E32").ClearContents
Range("G3").Value = Date
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
Sub SavePOWithNewName()
Dim NewFN As Variant
' Copy PO to a new workbook
ActiveSheet.Copy
NewFN = "Y:\YS-SBS2011YSL Purchase OrderYSL-PO" & Range("G4") & Range("G3").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
NextPO
End Sub
you don’t call a sub with the title
NextPO will have to exist in the workbook already to avoid an error
-
#3
Hello Jessica
I think the problem is that you have two sets of Sub for each procedure and only one End Sub
Try commenting out the second one by adding a quoute mark like this before Sub:
‘Sub NextPO()
-
#4
I’m not sure what you mean by this? What should I change? Add? Amend?
-
#5
I’m not sure what you mean by this? What should I change? Add? Amend?
Im saying that you have two separate sub names for each of your procedures, and only one End Sub. When the cumputer goes past the End Sub, it finds that there is no End Sub to match the second sub name, so you get the error «(I) Expected (an) End Sub».
So …. If you tell it to ignore one of the sub names everything will be OK
You can make VBA iignore a line of code by putting a quote mark (‘) at the start of the line.
Rich (BB code):
Private Sub Workbook_Open()
'Sub NextPO() This line will be ignored because of the ' mark
Range("G4").Value = Range("G4").Value + 1
Range("A16:E32").ClearContents
Range("G3").Value = Date
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'Sub SavePOWithNewName() This Line will also be ignored
Dim NewFN As Variant
' Copy PO to a new workbook
ActiveSheet.Copy
NewFN = "Y:\YS-SBS2011YSL Purchase OrderYSL-PO" & Range("G4") & Range("G3").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
NextPO
End Sub
Last edited: Oct 14, 2014
-
#6
Sorry Jessica — Im having a bad day
I see your trying to NextPO as part of the Worksheet Change module so we need to keep it. The problem is you can’t start to define NextPO from within another procedure that is incomplete as your doing.
It would need to be defined separately and then used rather that defined in Workbook Open (Done by stating it without the sub qualifier which means its being defined. This arrangement should work without errors:
Code:
Private Sub Workbook_Open()
NxtPO
End Sub
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
SavePOWithNewName
End Sub
Sub SavePOWithNewName()
Dim NewFN As Variant
' Copy PO to a new workbook
ActiveSheet.Copy
NewFN = "Y:\YS-SBS2011YSL Purchase OrderYSL-PO" & Range("G4") & Range("G3").Value & ".xlsx"
ActiveWorkbook.SaveAs NewFN, FileFormat:=xlOpenXMLWorkbook
ActiveWorkbook.Close
NxtPO
End Sub
Sub NxtPO()
Range("G4").Value = Range("G4").Value + 1
Range("A16:E32").ClearContents
Range("G3").Value = Date
End Sub
-
#7
Thank you sooo much for your help!
This code seems to work and is inputting the sequential numbers, yay! It is saving the file correctly on opening too buuuuuut………. its saving the file over and over and over again and I can’t stop it! How can I get into the file to work on the code if it’s constantly resaving and I can’t get it to stay on the original!? And what is it that I need to change in the code to make the resave only happen the one time per opening…
GTO
MrExcel MVP
-
#8
Please can someone help! I’ve never written a macro before! I’ve got this far but keep getting the same error message and despite reading numerous forums for advice, I can’t see where I’ve gone wrong!
I am trying to create a Purchase Order template that will open with a new sequential number each time and will force a new file name when saved, ideally the name to be the sequential number… If it cooooould, I’d quite like the date to drop in upon opening as well
…
Hi Jessica,
Off to the rack shortly, but for any «helper», could you expound a bit on this?
In really plain-English, please tell us what you would like the Template to do?
By utter guessing and most likely off-the-mark, but by example nevertheless:
«I have an Excel Template. Upon creating a new workbook based on this template, I would like….» to happen.
Mark
-
#9
Hi Jessica,
Off to the rack shortly, but for any «helper», could you expound a bit on this?
In really plain-English, please tell us what you would like the Template to do?
By utter guessing and most likely off-the-mark, but by example nevertheless:
«I have an Excel Template. Upon creating a new workbook based on this template, I would like….» to happen.
Mark
Hi Mark,
Thanks so much for coming back to me…
I want to have Purchase Order template that will know what the next available PO number is…
So, I want the excel sheet to open with the next sequential number from when previously opened. I then want it to save with this sequential number as the file name.
So… the first one would be PO001 (in the field G4 in my case) and then auto-saved as ‘YSL-PO001’. The next time its opened, if it could then say PO002 and will auto-save as ‘YSL-PO002’. Ideally this should stop duplications and will make sure that all PO’s are saved…
If I could ask for more, I’d also like it to drop ‘today’s date’ in the G3 box but this isn’t essential…
What do you think? Thanks again in advance,
Jessica
-
#10
Thank you sooo much for your help!
This code seems to work and is inputting the sequential numbers, yay! It is saving the file correctly on opening too buuuuuut………. its saving the file over and over and over again and I can’t stop it! How can I get into the file to work on the code if it’s constantly resaving and I can’t get it to stay on the original!? And what is it that I need to change in the code to make the resave only happen the one time per opening…
Hi Jessica
Im glad we are getting a bit closer, but GTO is right that without a clear picture of the objective, we can only try to get your code executing without error, but it could be doing the wrong thing!
Lets look at what we have in the code (post #6)
1. You have a WorkbookOpen Sub, which will execute whenever the workbook containing it is opened. This adds 1 to the value in cell G4, puts the date in G3 and clears cells A16-E32 (Active Worksheet) {sub NxtPO}
2. You also have a WorksheetChange module, which I assume is attached to the active worksheet containng your Counter in G4, and there is the problem. This routine saves the ActiveWorksheet with a new name and increments
your counter , changing the activesheet, which runs the module again.
To resolve, you can either put the counter in a different worksheet, or amend the worksheet change routine to ignore a change to cell G4.
Just one more point: You do appreciate that a new workbook will be saved for every single change to the worksheet that has the change module ?
Last edited: Oct 15, 2014