I’m having an issue with a VBA program I made. I want to create a program which inputs 50,000 records throughout a table (which is the Employee Table in my case), and every time I try to run it, it states an error that says "Compile Error: Duplicate declaration in current scope."
My code is as follows:
Option Compare Database
Option Explicit
Sub arrayData1()
'This subroutine will pump in 50 k records for the first two columns of EMPLOYEE table.
'Also takes in sample names, attempts to clean the data beofre its entered in the table.
'Declare variable by using keyword DIM
Dim EmployeeFNames() As Variant 'implies array. array is always declared variant datatype.
Dim EmployeeLNames() As Variant
Dim EmployeeType() As Variant
Dim num As Integer, dbs As Database, InsertRecord As Variant, num1 As Long
Dim EmployeeID As Long, EmployeeFName As String, EmployeeLName As String, EmployeeType As String, EmployeeWages As Long
'assign value to variables
Set dbs = CurrentDb() 'assign current db(Stage 2 Project)
EmployeeID = 0 'initialise value.
For num1 = 0 To 50000
EmployeeID = EmployeeID + 1 'increment by 1.
EmployeeWages = EmployeeWages + 1
' array is populated with names.
EmployeeFNames = Array("Peter", "Mary", "Frances", "Paul", "Ian", "Ron", "Nathan", "Jesse", "John", "David")
EmployeeLNames = Array("Jacobs", "Smith", "Zane", "Key", "Doe", "Patel", "Chalmers", "Simpson", "Flanders", "Skinner")
EmployeeTypes = Array("Groundskeeper", "Housekeeper", "Concierge", "Front Desk", "Chef", "F&B", "Maintenance", "Accounts", "IT", "Manager")
'Equation for random generation
'INT (upperbound - lowerbound +1) * Rnd + lowerbound) ' upper & lower bound are index values of array
num = Int((9 - 0 + 1) * Rnd + 0) ' equation generates at random a number between 0 & 9.
EmployeeFName = EmployeeFNames(num) ' name is picked at random from array based on random number.
EmployeeLName = EmployeeLNames(num)
EmployeeType = EmployeeTypes(num)
' Use SQL INSERT statement to insert record in EPLOYEE table.
InsertRecord = "INSERT INTO EMPLOYEE(EmployeeID, EmployeeFName, EmployeeLName, EmployeeType, EmployeeWages) VALUES(" _
& "'" & EmployeeID & "'" & "," & "'" & EmployeeFName & "'" & "," & "'" & EmployeeLName & "'" & "," & "'" & EmployeeType & "'" & "," & "'" & EmployeeWages & "'" & ")"
dbs.Execute InsertRecord
Debug.Print EmployeeID; EmployeeFName; EmployeeLName; EmployeeType; EmployeeWages
Next
End Sub
I would appreciate any fixes to this problem and any suggestions towards my code.
Permalink
Cannot retrieve contributors at this time
title | keywords | f1_keywords | ms.prod | ms.assetid | ms.date | ms.localizationpriority |
---|---|---|---|---|---|---|
Duplicate declaration in current scope |
vblr6.chm1011221 |
vblr6.chm1011221 |
office |
55b4c056-c787-b30a-bc8c-30e552a3cdbb |
06/08/2017 |
medium |
The specified name is already used at this level of scope. For example, two variables can have the same name if they are defined in different procedures, but not if they are defined within the same procedure. This error has the following causes and solutions:
-
A new variable or procedure has the same name as an existing variable or procedure. For example:
Sub MySub() Dim A As Integer Dim A As Variant . . . ' Other declarations or procedure code here. End Sub
Check the current procedure, module, or project and remove any duplicate declarations.
-
A Const statement uses the same name as an existing variable or procedure. Remove or rename the constant in question.
-
You declared a fixed array more than once.
Remove or rename one of the arrays.
Search for the duplicate name. When specifying the name to search for, omit any type-declaration character because a conflict occurs if the names are the same and the type-declaration characters are different.
Note that a module-level variable can have the same name as a variable declared in a procedure, but when you want to refer to the module-level variable within the procedure, you must qualify it with the module name. Module names and the names of referenced projects can be reused as variable names within procedures and can also be qualified.
For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).
[!includeSupport and feedback]
янеты Пользователь Сообщений: 21 |
#1 15.04.2017 12:17:02 Крепкого Всем Здоровья! Можно ли помочь ученику? В макросе есть две такие штучки, поотдельности каждая работает, вместе пишет: Duplicate declaration in current scope. Поиск по форуму и инету никак не хочет помогать:). Заранее благодарен всем.
|
||
RAN Пользователь Сообщений: 7139 |
Двойное объявление в текущей области действия И, кстати, в том обрывке кода, который вы приложили, этой ошибки не будет. |
янеты Пользователь Сообщений: 21 |
Как бы я этого хотел! Есть эта ошибка если два этих действия делать подряд в одном макросе! Из инета понял надо что то переименовать вроде, но что и где, моего умишка не хватает… |
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
#4 15.04.2017 12:57:51
вырезать и вставить перед:
Оформляйте код кнопкой <…>
|
||||
янеты Пользователь Сообщений: 21 |
#5 15.04.2017 13:24:27 Что надо изменить чтоб работало? Заранее спасибо.
Изменено: янеты — 15.04.2017 14:49:44 |
||
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
#6 15.04.2017 13:27:46
1) оформить код как полагается;
|
||
RAN Пользователь Сообщений: 7139 |
#7 15.04.2017 13:31:10
Эту часть
Вам слово Duplicate ничего не говорит? Я даже перевел Гуглом. Изменено: RAN — 15.04.2017 21:17:48 |
||||
янеты Пользователь Сообщений: 21 |
Извините меня не опытного, я не знаю как правильно оформлять код, только учусь писать макрос, (для меня большой Изменено: янеты — 15.04.2017 14:58:26 |
JayBhagavan Пользователь Сообщений: 11833 ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64 |
янеты, я Вам про код в сообщении форума. Посмотрите как у меня код оформлен и сделайте также при помощи кнопки на панели формы ответов форума, о которой я Вам ранее говорил и показал, как она выглядит. Это никак не связано с Вашим умением писать макросы.
|
янеты Пользователь Сообщений: 21 |
Я тоже перевел, и в название темы вынес. Из за неопытности не понимаю как один дубликат переделать до рабочего состояния … Если это нельзя сделать буду искать другие решения… |
Юрий М Модератор Сообщений: 60761 Контакты см. в профиле |
#11 15.04.2017 14:31:47
Для того, чтобы оформить код должным образом, умения писать макросы не нужно — ищите такую кнопку и исправьте своё сообщение. Прикрепленные файлы
|
||
янеты Пользователь Сообщений: 21 |
#12 15.04.2017 14:32:04
|
||
RAN Пользователь Сообщений: 7139 |
#13 15.04.2017 14:33:02
Конечно нельзя, ибо код вы не показываете.
Никак. Их быть не должно. |
||||
янеты Пользователь Сообщений: 21 |
иду по такому пути Прикрепленные файлы
|
Михаил Лебедев Пользователь Сообщений: 2860 |
#15 15.04.2017 15:26:45 А где файл с макросом?
или так?
или вот так?
Изменено: Михаил Лебедев — 15.04.2017 15:29:07 Всё сложное — не нужно. Всё нужное — просто /М. Т. Калашников/ |
||||||||
янеты Пользователь Сообщений: 21 |
#16 15.04.2017 16:24:43 УРА!!! Заработало!
Изменено: янеты — 15.04.2017 16:39:52 |
||
RAN Пользователь Сообщений: 7139 |
#17 15.04.2017 20:02:19 Михаил Лебедев, |
Go to excel
r/excel
r/excel
Ask and answer questions about Microsoft Excel or other spreadsheet applications. Or discuss anything Excel.
Members
Online
•
by
ss90kim
Getting error for macro. Compile error: Duplicate declaration in current scope.
I’m using the following code for sheet1 and sheet2.
Dim endRow As Long endRow = Cells(Rows.Count, "A").End(x1Up).Row
I’m getting error on the endRow. Do I just need to change the variable name to something else like «lastRow»?
It looks like you haven’t closed your With statement with and «End with»
Here’s my code:
Code:
Sub PerformAllTasks()
' Turn off screen updating
Application.ScreenUpdating = False
' Create new workbook called amanda_receipts and convert content from amanda_receipts.csv to xlsx
Workbooks.Add
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;V:VMI Reportsamanda_receipts.csv", Destination:=Range("$A$1"))
.Name = "amanda_receipts"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = False
.TextFileSemicolonDelimiter = True
.TextFileCommaDelimiter = False
.TextFileSpaceDelimiter = False
.TextFileOtherDelimiter = "|"
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
ActiveWorkbook.SaveAs Filename:="V:VMI Reportsamanda_receipts.xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
ActiveWorkbook.Save
ActiveWorkbook.Close
' UnhideAmandaReceipts
Sheets("728101").Select
Sheets("amanda_receipts").Visible = True
' OneOpenandCopyamanda_receiptsxlsx Macro
Workbooks.Open Filename:= _
"V:VMI Reportsamanda_receipts.xlsx"
Columns("A:Q").Select
Selection.Copy
Windows("MASTER - Amanda Receipts.xlsm").Activate
Sheets("amanda_receipts").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Windows("amanda_receipts.xlsx").Activate
Application.CutCopyMode = False
ActiveWorkbook.Close
' TwoSearchReplaceHLK
Windows("MASTER - Amanda Receipts.xlsm").Activate
Columns("E:E").Select
Selection.Replace What:="*HLK", Replacement:="HLK", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("A1").Select
' ThreeSortbyQthenA
ActiveWorkbook.Worksheets("amanda_receipts").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("amanda_receipts").Sort.SortFields.Add Key:=Range( _
"Q2:Q3625"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
ActiveWorkbook.Worksheets("amanda_receipts").Sort.SortFields.Add Key:=Range( _
"A2:A3625"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
xlSortNormal
With ActiveWorkbook.Worksheets("amanda_receipts").Sort
.SetRange Range("A1:Q3625")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A1").Select
' FourUnhide Tabs
Sheets("amanda_receipts").Select
Sheets("WhsList1").Visible = True
Sheets("WhsList1").Select
Sheets("Pivot").Visible = True
Sheets("Pivot").Select
Sheets("WhsList2").Visible = True
Sheets("amanda_receipts").Select
' FiveOpenOnHandandCopy
Workbooks.Open Filename:= _
"V:VMI ReportsOn-Hand.xlsx"
Columns("I:J").Select
Selection.Copy
Windows("MASTER - Amanda Receipts.xlsm").Activate
Sheets("WhsList1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Range("A1").Select
Sheets("amanda_receipts").Select
' SixRefreshPivot
Sheets("Pivot").Select
Range("A1").Select
Application.CutCopyMode = False
ActiveWorkbook.RefreshAll
Sheets("amanda_receipts").Select
' SevenPivotRemoveBlanks
Sheets("Pivot").Select
With ActiveSheet.PivotTables("PivotTable6").PivotFields("Warehouse")
.PivotItems("(blank)").Visible = False
End With
Sheets("amanda_receipts").Select
' EightCopyPivottoWhsList2
Sheets("Pivot").Select
Columns("A:B").Select
Selection.Copy
Sheets("WhsList2").Select
Range("A1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("A:B").EntireColumn.AutoFit
Range("A2").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Range("A2").Select
Range(Selection, Selection.End(xlDown)).Select
Columns("A:A").Select
Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
Semicolon:=False, Comma:=False, Space:=False, Other:=True, OtherChar _
:="|", FieldInfo:=Array(1, 1), TrailingMinusNumbers:=True
Sheets("amanda_receipts").Select
Range("A1").Select
' NineRefreshPivots
Sheets("Pivot").Select
Range("A1").Select
Application.CutCopyMode = False
ActiveWorkbook.RefreshAll
Sheets("amanda_receipts").Select
' TenHide Macro
Sheets(Array("WhsList1", "Pivot", "WhsList2")).Select
Sheets("WhsList2").Activate
ActiveWindow.SelectedSheets.Visible = False
Sheets("amanda_receipts").Select
Range("A1").Select
' ElevenCloseOnHandDetails
Windows("On-Hand.xlsx").Activate
Range("A2").Select
ActiveWorkbook.Close
' HideAmandaReceiptsTab
Sheets("amanda_receipts").Select
ActiveWindow.SelectedSheets.Visible = False
Range("A1").Select
' Save workbook as XLSX file and append date
ActiveWorkbook.SaveAs Filename:="V:VMI ReportsVMI Report - ALL" & Format(Now, " mm-dd-yyyy"), FileFormat:=51
' Turn on screen updating
Application.ScreenUpdating = True
' Save each tab as a different workbook
Dim wb As Workbook
Sheets("728101").Copy
Set wb = ActiveWorkbook
With wb
ActiveWorkbook.SaveAs Filename:="V:VMI ReportsReportsVMI Report - ACBEL" & Format(Now, " mm-dd-yyyy"), FileFormat:=51
.Close False
End With
Sheets("728103").Copy
Set wb = ActiveWorkbook
With wb
ActiveWorkbook.SaveAs Filename:="V:VMI ReportsReportsVMI Report - AVC" & Format(Now, " mm-dd-yyyy"), FileFormat:=51
.Close False
Sheets("728104").Copy
Set wb = ActiveWorkbook
With wb
ActiveWorkbook.SaveAs Filename:="V:VMI ReportsReportsVMI Report - CAREER" & Format(Now, " mm-dd-yyyy"), FileFormat:=51
.Close False
Sheets("728105").Copy
Set wb = ActiveWorkbook
With wb
ActiveWorkbook.SaveAs Filename:="V:VMI ReportsReportsVMI Report - DELTA" & Format(Now, " mm-dd-yyyy"), FileFormat:=51
.Close False
Sheets("728106").Copy
Set wb = ActiveWorkbook
With wb
ActiveWorkbook.SaveAs Filename:="V:VMI ReportsReportsVMI Report - HAMANAKA" & Format(Now, " mm-dd-yyyy"), FileFormat:=51
.Close False
Sheets("728107").Copy
Set wb = ActiveWorkbook
With wb
ActiveWorkbook.SaveAs Filename:="V:VMI ReportsReportsVMI Report - AVC" & Format(Now, " mm-dd-yyyy"), FileFormat:=51
.Close False
End With
End Sub
Even with an End With in the code I get a Compile Error: Expected End With