Меню

Sub main visual basic ошибка

Permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: BC30420: ‘Sub Main’ was not found in ‘<name>’

‘Sub Main’ was not found in ‘<name>’

07/20/2015

vbc30420

bc30420

BC30420

Sub Main error message

a006d57d-4dd3-46a7-9026-ca9a31470da7

Sub Main is missing, or the wrong location has been specified for it.

Error ID: BC30420

To correct this error

  1. Supply the missing Sub Main statement, or if it exists, move it to the appropriate location in the code. For more information on Sub Main, see Main Procedure in Visual Basic.

  2. Specify the location of the project’s startup object in the Startup form box of the Project Designer.

See also

  • Sub Statement
  • Main Procedure in Visual Basic

  • Remove From My Forums
  • Question

  • Okay, another question somewhat releated to my previous post, but I feel that it is worthy of a seperate thread.

    Code Block

    Module mainModule
        Sub Main(ByVal args() As String)
                  MsgBox(«Hello Workd»)
        End Sub
    End Module

    When i type the following into the cmd prompt to compile

    vbc.exe mainModule.vb /main:MainModule.vb

    I get the following error

    vbc : error BC30420: ‘Sub Main’ was not found in ‘mainmodule.vb’.

    Why is it saying that no ‘Sub Main’ was not found when it is there?

Answers

  • Try to change the startup from Project -> Properties -> Debug Section. Hope it solves your problem

  • Code Block

    Module mainModule
        Sub Main()
                  MsgBox(«Hello Workd»)
        End Sub
    End Module

    this will fix your problem

  • Use the following

    vbc.exe mainModule.vb

    This will compile or work

    or if you want to use the /main switch then use the following.  The last .vb you previously had used is screwing things up.   It is looking for a class name not a filename — hence the .vb is the filename not the classname.

    So the following will work

    vbc.exe mainModule.vb /main:MainModule

Аня_Самойлова

0 / 0 / 0

Регистрация: 24.08.2018

Сообщений: 60

1

01.10.2018, 19:04. Показов 7923. Ответов 10

Метки ООП (Все метки)


VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
Imports System.IO
Module Program
    'Базовый абстрактный класс
    MustInherit Class КлассТовар
        'Поля для описания персоны
        Public Наименование As String
        Public Страна As String
        Public Количество_единиц_товара As String
        Public Дата_доставки As Date
        'Переопределяемый метод для ввода полей
        Public Overridable Sub Ввести()
            Console.WriteLine("Сведения о товаре")
            Console.Write(ControlChars.Tab & "Наименование: ")
            Наименование = Console.ReadLine()
            Console.Write(ControlChars.Tab & "Страна: ")
            Страна = Console.ReadLine()
            Console.Write(ControlChars.Tab & "Количество_единиц_товара: ")
            Количество_единиц_товара = Console.ReadLine()
            Console.Write(ControlChars.Tab & "Дата_доставки: ")
            Дата_доставки = Console.ReadLine()
        End Sub
    End Class
    Class КлассМолочные
        Inherits КлассТовар 'Унаследован от класс персона
        Public Срок_годности As Integer 'Частное свойство
 
        Overrides Sub Ввести()
            MyBase.Ввести()
            Console.WriteLine("Срок: {0}", Срок_годности)
        End Sub
    End Class
    Class КлассКондитерские
        Inherits КлассТовар 'унаследовани от класс персона
        Public Вес As Integer 'Частное свойство
 
        Overrides Sub Ввести()
            MyBase.Ввести()
            Console.WriteLine("Вес: {0}", Вес)
        End Sub
    End Class
 
    Class КлассСклад
        Public Товар() As КлассТовар
        Public МолТовары() As КлассМолочные
        Public КонТовары() As КлассКондитерские
        Public Sub Ввести()
            Dim i, n As Integer
            Console.WriteLine("Склад")
            Console.Write("Количество молочных товаров(видов): ")
            n = Console.ReadLine()
            МолТовары = New КлассМолочные(n - 1) {}
            For i = 0 To UBound(МолТовары)
 
 
                'Создание для экземпляра для первого товара
                МолТовары(i) = New КлассМолочные
                МолТовары(i).Ввести()
            Next
 
            Console.Write("Количество кондитерских  товаров(видов): ")
            n = Console.ReadLine()
            КонТовары = New КлассКондитерские(n - 1) {}
            For i = 0 To UBound(КонТовары)
 
 
                'Создание для экземпляра для первого товара
                КонТовары(i) = New КлассКондитерские
                КонТовары(i).Ввести()
            Next
        End Sub
    End Class
    Sub Main()
        Dim Товар As КлассТовар
        Товар.Ввести()
        'Вывести наименование продуктов которые привезли в опр дату
        Console.WriteLine("Введите дату: ")
        Dim Дата As Date = Console.ReadLine()
        Console.WriteLine("Наименование продуктов привезенных в этот срок: ")
        'For Each Товар As КлассТовар In Товар
        If Товар.Дата_доставки = Дата Then
                Console.WriteLine(Товар.Наименование)
            End If
 
        Console.ReadKey()
    End Sub
End Module

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



XIST

1274 / 979 / 137

Регистрация: 01.10.2009

Сообщений: 3,092

Записей в блоге: 1

01.10.2018, 19:31

2

Аня_Самойлова, так его и нету

VB.NET
1
2
3
  Sub Main() 'начало объявления метода
 
    End Sub 'конец объявления метода



0



0 / 0 / 0

Регистрация: 24.08.2018

Сообщений: 60

01.10.2018, 19:42

 [ТС]

3

На строчке 72 же объявляется



0



1274 / 979 / 137

Регистрация: 01.10.2009

Сообщений: 3,092

Записей в блоге: 1

01.10.2018, 19:46

4

Аня_Самойлова, именно в базовом классе его нет



0



ovva

4201 / 3354 / 813

Регистрация: 02.02.2013

Сообщений: 3,254

Записей в блоге: 2

01.10.2018, 19:49

5

Вынесите определение класса за границы модуля.

VB.NET
1
2
3
4
5
6
7
8
9
10
Module Module1
    Sub Main()
        Dim Товар As New КлассТовар
'…
        Console.ReadKey()
    End Sub
End Module
Public Class КлассТовар
'…
End Class

Если вы хотите непосредственно использовать класс КлассТовар то он не может быть MustInherit (к тому же определенные наследники нигде далее не используются).



0



0 / 0 / 0

Регистрация: 24.08.2018

Сообщений: 60

01.10.2018, 19:56

 [ТС]

6

ту же ошибку показывает(



0



4201 / 3354 / 813

Регистрация: 02.02.2013

Сообщений: 3,254

Записей в блоге: 2

01.10.2018, 20:07

7

Выложите ваш проект целиком.



0



4201 / 3354 / 813

Регистрация: 02.02.2013

Сообщений: 3,254

Записей в блоге: 2

01.10.2018, 20:24

8

Пример



0



Аня_Самойлова

0 / 0 / 0

Регистрация: 24.08.2018

Сообщений: 60

01.10.2018, 20:48

 [ТС]

9

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
Imports System.IO
Module Module1
 
    'Базовый абстрактный класс
 
    Sub Main()
        Dim Товар As КлассТовар
        Товар.Ввести()
        'Вывести наименование продуктов которые привезли в опр дату
        Console.WriteLine("Введите дату: ")
        Dim Дата As Date = Console.ReadLine()
        Console.WriteLine("Наименование продуктов привезенных в этот срок: ")
        'For Each Товар As КлассТовар In Товар
        If Товар.Дата_доставки = Дата Then
            Console.WriteLine(Товар.Наименование)
        End If
 
        Console.ReadKey()
    End Sub
End Module
MustInherit Class КлассТовар
        'Поля для описания персоны
        Public Наименование As String
        Public Страна As String
        Public Количество_единиц_товара As String
        Public Дата_доставки As Date
        'Переопределяемый метод для ввода полей
        Public Overridable Sub Ввести()
            Console.WriteLine("Сведения о товаре")
            Console.Write(ControlChars.Tab & "Наименование: ")
            Наименование = Console.ReadLine()
            Console.Write(ControlChars.Tab & "Страна: ")
            Страна = Console.ReadLine()
            Console.Write(ControlChars.Tab & "Количество_единиц_товара: ")
            Количество_единиц_товара = Console.ReadLine()
            Console.Write(ControlChars.Tab & "Дата_доставки: ")
            Дата_доставки = Console.ReadLine()
        End Sub
    End Class
 
    Class КлассМолочные
        Inherits КлассТовар 'Унаследован от класс персона
        Public Срок_годности As Integer 'Частное свойство
 
        Overrides Sub Ввести()
            MyBase.Ввести()
            Console.WriteLine("Срок: {0}", Срок_годности)
        End Sub
    End Class
    Class КлассКондитерские
        Inherits КлассТовар 'унаследовани от класс персона
        Public Вес As Integer 'Частное свойство
 
        Overrides Sub Ввести()
            MyBase.Ввести()
            Console.WriteLine("Вес: {0}", Вес)
        End Sub
    End Class
 
    Class КлассСклад
        Public Товар() As КлассТовар
        Public МолТовары() As КлассМолочные
        Public КонТовары() As КлассКондитерские
        Public Sub Ввести()
            Dim i, n As Integer
            Console.WriteLine("Склад")
            Console.Write("Количество молочных товаров(видов): ")
            n = Console.ReadLine()
            МолТовары = New КлассМолочные(n - 1) {}
            For i = 0 To UBound(МолТовары)
 
 
                'Создание для экземпляра для первого товара
                МолТовары(i) = New КлассМолочные
                МолТовары(i).Ввести()
            Next
 
            Console.Write("Количество кондитерских  товаров(видов): ")
            n = Console.ReadLine()
            КонТовары = New КлассКондитерские(n - 1) {}
            For i = 0 To UBound(КонТовары)
 
 
                'Создание для экземпляра для первого товара
                КонТовары(i) = New КлассКондитерские
                КонТовары(i).Ввести()
            Next
        End Sub
    End Class

Добавлено через 20 минут
Файл не открывается к сожалению



0



4201 / 3354 / 813

Регистрация: 02.02.2013

Сообщений: 3,254

Записей в блоге: 2

01.10.2018, 20:58

10

Цитата
Сообщение от Аня_Самойлова
Посмотреть сообщение

Файл не открывается к сожалению

Не открывается приложенный файл? Этот файл zip-архив, можно открыть любым архиватором. Внутри vb проект ConsoleApplication1 (загружается через файл ConsoleApplication1.sln).
PS. Я предполагал, что и вы свой проект выложите подобным образом.



0



0 / 0 / 0

Регистрация: 24.08.2018

Сообщений: 60

01.10.2018, 21:17

 [ТС]

11

эту проблему я решила)) файл что вы отправили действительно работает. Я постараюсь отправить свой zip



0



It’s actually a bit more complicated, and I fear you may have learned the wrong lesson from what DB suggested, useful though it may be.

As you might expect, every program has to know where to start. No matter what you write, it ends up being a series of VERY simple instructions, because that’s all that the CPU can do. All that higher level languages do is make it easier to create complex programs, but they all end up as a series of sequential instructions. You can see them as a stack of cards. When the program begins, it takes the first card from the stack and does what is on the card, then takes the next card from the stack and so on. It’s not quite that simple, as it can keep going back to earlier places in the stack and repeating steps, or even create a second process and move a selection of the cards over to that separate process so that both are going through their stacks of cards at the same time.

However, there always has to be that first card. By long standing tradition, that is Sub Main(). For a very long time, you could ALWAYS find Sub Main(), and that would be roughly where things started (some memory could be set up ahead of time, but nothing much). The first line in Sub Main was the first card in the stack.

With Windows programming in .NET, there is ALWAYS a Sub Main….but you can’t ALWAYS find it. You used to be able to, back in .NET 2002 and 2003, but since then it could be hidden. Windows programs usually begin with a startup form, in which case you’d have a hard time finding Sub Main, if you even can.

What DB showed you is the style that Windows applications had to follow back in 2002 and 2003, and which is still used for console apps as he demonstrated. If you create a Windows application rather than a console app, then you’ll have a startup form (which is usually the first one given to you, by default, though you are free to change that), and neither the module nor the Sub Main is necessary. In that case, the code you had would be fine as you had it, but you’d also have a startup form, which would hide the Sub Main from you.

A class library is a dll. You’ve doubtless seen a few items with that extension. The key point about a dll is that it doesn’t have a Sub Main, plain or hidden. Therefore, you can’t execute a dll because there is no starting point in it. Using the stack of cards analogy, you could say that a dll is one or more stacks of cards, but none of them is the first one. That type of project holds code and objects that will be used by one or more other projects. They can’t stand alone, because they can’t start on their own. They have to be included into some project that actually has a starting point. Once included in, they can be used by that other project. Typically, you create a dll to store methods and objects that you feel you’ll be able to use in multiple projects, though there are other uses for them, as well.

So, don’t feel that you MUST have a module and a Sub Main. You must have one for a console app, but need not write either one for a Windows forms app, and can’t have a meaningful Sub Main for a class library.

Muriithi Gakuru

It’s safe to say that Visual Basic has become one of the hardest languages to find content about online ever since Microsoft announced that there won’t be any more features added to it in .NET CORE/ .NET 5.

 “ Going forward, we do not plan to evolve Visual Basic as a language ”
.NET Team

That explained a lot when I tried to troubleshoot an error I’d gotten and the whole of the internet was almost blank, for an error I’d call trivial and noob level. I’ve recreated the above error so as to show you how to solve it. Save you time.

Screenshot (46).png

Every time I tried the compile and run the project, i got and error that the Sub Main()

was not found.
The solution to this is to check that the startup form isn’t referencing to an old method. You can find that in your project properties.

  1. All you have to do is right-click on your main project in the top-right area of the visual basic working area.

Screenshot (47).png

  1. Scroll to the bottom and click on properties.

Screenshot (48).png

On the new window right at the Startup Project section is where you’re going to change from
Sub Main

to the name of your Form.
Screenshot (49).png
Once you’re done, you can exit that tab and re-run your project.

Screenshot (51).png

Everything should be working fine and you can notice that the error is gone.

Conclusion

Every day is a coding challenge. If you feel that the content was inadequate please comment about it or contact me. Keep coding. Cheers !!

  • Remove From My Forums
  • Question

  • Okay, another question somewhat releated to my previous post, but I feel that it is worthy of a seperate thread.

    Code Block

    Module mainModule
        Sub Main(ByVal args() As String)
                  MsgBox(«Hello Workd»)
        End Sub
    End Module

    When i type the following into the cmd prompt to compile

    vbc.exe mainModule.vb /main:MainModule.vb

    I get the following error

    vbc : error BC30420: ‘Sub Main’ was not found in ‘mainmodule.vb’.

    Why is it saying that no ‘Sub Main’ was not found when it is there?

Answers

  • Try to change the startup from Project -> Properties -> Debug Section. Hope it solves your problem

  • Code Block

    Module mainModule
        Sub Main()
                  MsgBox(«Hello Workd»)
        End Sub
    End Module

    this will fix your problem

  • Use the following

    vbc.exe mainModule.vb

    This will compile or work

    or if you want to use the /main switch then use the following.  The last .vb you previously had used is screwing things up.   It is looking for a class name not a filename — hence the .vb is the filename not the classname.

    So the following will work

    vbc.exe mainModule.vb /main:MainModule

  • Remove From My Forums
  • Question

  • Okay, another question somewhat releated to my previous post, but I feel that it is worthy of a seperate thread.

    Code Block

    Module mainModule
        Sub Main(ByVal args() As String)
                  MsgBox(«Hello Workd»)
        End Sub
    End Module

    When i type the following into the cmd prompt to compile

    vbc.exe mainModule.vb /main:MainModule.vb

    I get the following error

    vbc : error BC30420: ‘Sub Main’ was not found in ‘mainmodule.vb’.

    Why is it saying that no ‘Sub Main’ was not found when it is there?

Answers

  • Try to change the startup from Project -> Properties -> Debug Section. Hope it solves your problem

  • Code Block

    Module mainModule
        Sub Main()
                  MsgBox(«Hello Workd»)
        End Sub
    End Module

    this will fix your problem

  • Use the following

    vbc.exe mainModule.vb

    This will compile or work

    or if you want to use the /main switch then use the following.  The last .vb you previously had used is screwing things up.   It is looking for a class name not a filename — hence the .vb is the filename not the classname.

    So the following will work

    vbc.exe mainModule.vb /main:MainModule

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Su41350 3 пс4 ошибка
  • Su 41350 3 ошибка ps4 что делать