For the life of me I cannot figure out why the following code is throwing a compile error with the message «Invalid outside procedure». It is highlighting the error on the starred line below.
Option Explicit
Dim shtThisSheet As Worksheets
**Set shtThisSheet = Application.Workbook("Formatting2.xlsm").Worksheets("Sheet1")**
Sub Formatting()
With shtThisSheet
With Range("A1")
.Font.Bold = True
.Font.Size = 14
.HorizontalAlignment = xlLeft
End With
With Range("A3:A6")
.Font.Bold = True
.Font.Italic = True
.Font.ColorIndex = 5
.InsertIndent 1
End With
With Range("B2:D2")
.Font.Bold = True
.Font.Italic = True
.Font.ColorIndex = 5
.HorizontalAlignment = xlRight
End With
With Range("B3:D6")
.Font.ColorIndex = 3
.NumberFormat = "$#,##0"
End With
End With
End Sub
Michael Liu
51.3k13 gold badges117 silver badges149 bronze badges
asked Feb 10, 2016 at 15:31
2
Set
statements aren’t allowed outside procedures. Move the Set
statement into the Formatting
procedure:
Sub Formatting()
Set shtThisSheet = Application.Workbook("Formatting2.xlsm").Worksheets("Sheet1")
...
(I’d move the Dim
statement into the procedure as well. I prefer to avoid global variables when possible.)
answered Feb 10, 2016 at 15:33
Michael LiuMichael Liu
51.3k13 gold badges117 silver badges149 bronze badges
3
You can declare variables as global, but you cannot set them outside of a procedure such as a sub or function.
If you need this variable as a global, then it’s best to set it on.
Workbook_Open()
If you do not need it as a global, then move both the declaration and the set statement into your procedure
answered Feb 10, 2016 at 18:36
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Invalid outside procedure |
vblr6.chm1040051 |
vblr6.chm1040051 |
office |
46c00b2b-c656-9ad4-bff9-d341a6a7ecd5 |
06/08/2017 |
medium |
The statement must occur within a Sub or Function, or a property procedure (Property Get, Property Let, Property Set). This error has the following cause and solution:
-
An executable statement, Static or ReDim, appears at module level.
Static is unnecessary at module level, since all module-level variables are static. Use Dim instead of ReDim at module level. To create a dynamic array at module level, declare it with Dim using empty parentheses.
Note At module level, you can use only comments and declarative statements, such as Const, Declare, Deftype, Dim, Option Base, Option Compare, Option Explicit, Option Private, Private, Public, and Type. The Sub, Function, and Property statements occur outside the body of their procedures, but within the procedure declaration.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
Правила форума
Темы, в которых будет сначала написано «что нужно сделать», а затем просьба «помогите», будут закрыты.
Читайте требования к создаваемым темам.
- Нырков Сергей
- Начинающий
- Сообщения: 17
- Зарегистрирован: 18.07.2009 (Сб) 18:19
Загадочное сообщение от VB»invalid outside procedure»
Здравствуйте Алексей. Вы никогда не встречались с ошибкой «invalid outside procedure»?, на перевод хватает даже моего английского, – но при чём здесь внешняя процедура, — происходит присвоение строковых значений элементам массива VB выделяет имено строковое значение, массив объявлен как строковый,любуюсь на это сообщение третий день,за это время 4 раза переустановил VB никаких мыслей нет, если можете помогите
С уважением Нырков Сергей
- alibek
- Большой Человек
- Сообщения: 14205
- Зарегистрирован: 19.04.2002 (Пт) 11:40
- Откуда: Russia
Re: Загадочное сообщение от VB»invalid outside procedure»
alibek » 18.07.2009 (Сб) 19:47
Перенес.
Первое предупреждение.
Lasciate ogni speranza, voi ch’entrate.
- iGrok
- Артефакт VBStreets
- Сообщения: 4272
- Зарегистрирован: 10.05.2007 (Чт) 16:11
- Откуда: Сетевое сознание
Re: Загадочное сообщение от VB»invalid outside procedure»
iGrok » 18.07.2009 (Сб) 21:24
Нырков Сергей писал(а):но при чём здесь внешняя процедура
Вашего английского таки не хватило. Outside относится не к «procedure» а к «invalid». Соответственно, кардинально меняется и перевод.
label:
cli
jmp label
- Нырков Сергей
- Начинающий
- Сообщения: 17
- Зарегистрирован: 18.07.2009 (Сб) 18:19
Re: Загадочное сообщение от VB»invalid outside procedure»
Нырков Сергей » 19.07.2009 (Вс) 13:02
Это ответ на ответ.Поставил русский VB и получил сообщение «плохая внешняя процедура» Так-что перевод не при чем.У меня происходит присвоение строковых значений (кирилица) элементам массива, VB выделяет имено строковое значение (между кавычками), массив объявлен как строковый,любуюсь на это сообщение третий день,за это время 4 раза переустановил VB никаких мыслей нет, если кто может помогитеЕщё способ получить это сообщение – использовать array и не важно какие данные помещать в массив результат будет тем-же выделение первого элемента в массиве
Пробовал вариант с collection то-же самое
Если вирус то уж больно экзотический
С уважением Нырков Сергей
- alibek
- Большой Человек
- Сообщения: 14205
- Зарегистрирован: 19.04.2002 (Пт) 11:40
- Откуда: Russia
Re: Загадочное сообщение от VB»invalid outside procedure»
alibek » 19.07.2009 (Вс) 13:48
Нырков Сергей писал(а):Это ответ на ответ.Поставил русский VB и получил сообщение «плохая внешняя процедура»
Не рекомендуется ходить на форум в нетрезвом виде. Перечитай еще раз текст сообщения и вникни в смысл фразы «недопустимо за пределами процедуры». Что значит «за пределами» понимаешь?
Lasciate ogni speranza, voi ch’entrate.
- Нырков Сергей
- Начинающий
- Сообщения: 17
- Зарегистрирован: 18.07.2009 (Сб) 18:19
Re: Загадочное сообщение от VB»invalid outside procedure»
Нырков Сергей » 19.07.2009 (Вс) 20:38
Большое- пребольшое СПАСИБО. Я-бы никогда не перевел invalid как недопустимо, у меня этот блок находится в секции general и руссифицировал мой экземпляр VB такой-же переводчик как я,т.е. в одном месте я допустил две ошибки 1)засунул присвоение в секцию general,2) особо не вдумывался при переводе. Ещё раз спасибо, и удачи всем нам
Вернуться в Visual Basic 1–6
Кто сейчас на конференции
Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 1
- Remove From My Forums
-
Question
-
Hello all,
I am trying to convert a string to UTF-8 in VBA-Excel, my final aim is to do URL-encoding to UTF-8.
After a lot of searches I found this code that can help me to implement, it uses the Encoding Class:
http://msdn.microsoft.com/en-us/library/system.text.encoding.aspxIt starts with:
Imports System
Imports System.Text
Imports Microsoft.VisualBasicBut when I put the code example in the excel-VBA editor I get an error «Invalid outside procedure».
Please help, what sould I do?
p.s: if anyone has an example that can implement all the URL encoding to UTF-8 I will be grathfull to.
Answers
-
This is VB.NET code and the classes/methods you want to use cannot be used in VBA directly. What you can do is to look for a replacement which can be used in VBA directly or to create a VB.NET DLL, expose the desired functionality to COM and then
reference the .NET assembly (or more specifically, the TLB) from VBA. However, I’d recomment to take the first of the two ways I described.
Herfried K. Wagner [MVP]
-
Marked as answer by
Saturday, June 26, 2010 2:48 PM
-
Marked as answer by
-
If you want to ask your question in the VBA forum you can find it here
http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/c147bae1-c9db-4ae8-9557-43713004cc94
Coding4fun Be a good forum member mark posts that contain the answers to your questions or those that are helpful
Please format the code in your posts with thebutton . Makes it easier to read . Or use the Forum Code Formatter by JohnWein http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/bf977a14-d9d4-4e84-9784-bf76b9e23261
-
Marked as answer by
Liliane Teng
Saturday, June 26, 2010 2:48 PM
-
Marked as answer by
-
Hello elAlladin,
Thanks for your post.
VBA stands for Visual Basic for Applications which is available in Excel, and other office applications.
About VB.net, one can create a stand-alone windows application, which is not possible with VBA.
Check the following link about their detailed difference. Hope it helpful.
http://allfaq.org/forums/t/178686.aspx
http://answers.google.com/answers/threadview/id/217809.htmlThis forum is for VB.NET questions only (e.g. Visual Basic 2003, Visual Basic 2005, Visual Basic 2008).
For VBA questions,you could post it on VBA forums as bdbodger suggested for better and quicker support.Best regards,
Liliane
Please mark the replies as answers if they help and unmark them if they provide no help. Thanks
-
Marked as answer by
Liliane Teng
Saturday, June 26, 2010 2:48 PM
-
Marked as answer by
invalid outside procedure |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |
||||||||
Ответить |