Compile error duplicate declaration in current scope

Крепкого Всем Здоровья! Можно ли помочь ученику? В макросе есть две такие штучки, поотдельности каждая работает, вместе пишет:  Duplicate declaration in current scope. Поиск по форуму и инету никак не хочет помогать:). Заранее благодарен всем.Код x = ("Движение") 'удалить строки со словом       For i = Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1       If Cells(i, 2) = x Then Rows(i).Delete...
 

янеты

Пользователь

Сообщений: 21
Регистрация: 21.06.2016

#1

15.04.2017 12:17:02

 Крепкого Всем Здоровья! Можно ли помочь ученику? В макросе есть две такие штучки, поотдельности каждая работает, вместе пишет:  Duplicate declaration in current scope. Поиск по форуму и инету никак не хочет помогать:). Заранее благодарен всем.

Код
x = ("Движение") 'удалить строки со словом
      For i = Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
      If Cells(i, 2) = x Then Rows(i).Delete
      Next
          
      Dim x As Integer  'добавить строки
          x = Sheets("Лист28").Range("V7")
          y = Sheets("Лист28").Range("W7")
          Rows(y).Resize(x).Insert
 

RAN

Пользователь

Сообщений: 7081
Регистрация: 21.12.2012

Двойное объявление в текущей области действия

И, кстати, в том обрывке кода, который вы приложили, этой ошибки не будет.

 

янеты

Пользователь

Сообщений: 21
Регистрация: 21.06.2016

Как бы я этого хотел! Есть эта ошибка если два этих действия делать подряд в одном макросе! Из инета понял надо что то переименовать вроде, но что и где, моего умишка не хватает…

 

JayBhagavan

Пользователь

Сообщений: 11833
Регистрация: 17.01.2014

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

#4

15.04.2017 12:57:51

Код
Dim x As Integer 'добавить строки 

вырезать и вставить перед:

Код
x = ("Движение") 'удалить строки со словом 

Оформляйте код кнопкой <…>

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

янеты

Пользователь

Сообщений: 21
Регистрация: 21.06.2016

#5

15.04.2017 13:24:27

Что надо изменить чтоб работало?  Заранее спасибо.

Код
Sub asd()

' asd Макрос 

' здесь строки макроса, потом
   
      x = ("Движение") 'убрать строки со словом "движение"
      For i = Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
      If Cells(i, 2) = x Then Rows(i).Delete
      Nexт

 ' продолжение макроса, потом

      Dim x As Integer  ' добавить пустых строк до 15
          x = Sheets("ЕСТЬ").Range("V7")
          y = Sheets("ЕСТЬ").Range("W7")
          Rows(y).Resize(x).Insert

 '  продолжение макроса
      
End Sub

Изменено: янеты15.04.2017 14:49:44

 

JayBhagavan

Пользователь

Сообщений: 11833
Регистрация: 17.01.2014

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

#6

15.04.2017 13:27:46

Цитата
янеты написал: Что надо изменить чтоб работало?

1) оформить код как полагается;
2) название темы, имхо, неясное — в двух словах, в чём задача у Вас;
3) приложить файл с исх. данными и что должно получиться после работы макроса (сделано Вами вручную).

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

RAN

Пользователь

Сообщений: 7081
Регистрация: 21.12.2012

#7

15.04.2017 13:31:10

Цитата
янеты написал: Что надо изменить чтоб работало?

Эту часть

Цитата
янеты написал: ‘ здесь строки макроса

Вам слово Duplicate ничего не говорит? Я даже перевел Гуглом.

Изменено: RAN15.04.2017 21:17:48

 

янеты

Пользователь

Сообщений: 21
Регистрация: 21.06.2016

Извините меня не опытного, я не знаю как правильно оформлять код, только учусь писать макрос, (для меня большой :) ),  в котором надо преобразовать документ, в том числе в одном месте удалить строки со словом «Движение» , а в другом добавить пустые строки по условию. Т.к. сам не умею, с инета подбираю похожие макросы и подгоняю под себя. На данном этапе эти два куска при запуске в Visual Basic по отдельности работают, а вместе  конфликтуют.

Изменено: янеты15.04.2017 14:58:26

 

JayBhagavan

Пользователь

Сообщений: 11833
Регистрация: 17.01.2014

ПОЛ: МУЖСКОЙ | Win10x64, MSO2019x64

янеты, я Вам про код в сообщении форума. Посмотрите как у меня код оформлен и сделайте также при помощи кнопки на панели формы ответов форума, о которой я Вам ранее говорил и показал, как она выглядит. Это никак не связано с Вашим умением писать макросы.

<#0>
Формула массива (ФМ) вводится Ctrl+Shift+Enter
Memento mori

 

янеты

Пользователь

Сообщений: 21
Регистрация: 21.06.2016

Я тоже перевел, и в название темы вынес. Из за неопытности не понимаю как один дубликат переделать до рабочего состояния … Если это нельзя сделать буду искать другие решения…

 

Юрий М

Модератор

Сообщений: 60383
Регистрация: 14.09.2012

Контакты см. в профиле

#11

15.04.2017 14:31:47

Цитата
янеты написал:
я не знаю как правильно оформлять код, только учусь писать макрос

Для того, чтобы оформить код должным образом, умения писать макросы не нужно — ищите такую кнопку и исправьте своё сообщение.

Прикрепленные файлы

  • Тег VBA.jpg (19.2 КБ)

 

янеты

Пользователь

Сообщений: 21
Регистрация: 21.06.2016

#12

15.04.2017 14:32:04

Код
' asd Макрос
      
      x = ("Движение") 'убрать строки со словом "движение"
      For i = Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
      If Cells(i, 2) = x Then Rows(i).Delete
      Next
          
       Dim x As Integer ' добавить пустых строк до15
          x = Sheets("ЕСТЬ").Range("V7")
          y = Sheets("ЕСТЬ").Range("W7")
          Rows(y).Resize(x).Insert
      
End Sub
 

RAN

Пользователь

Сообщений: 7081
Регистрация: 21.12.2012

#13

15.04.2017 14:33:02

Цитата
янеты написал:
Если это нельзя сделать буду искать другие решения…

Конечно нельзя, ибо код вы не показываете.

Цитата
янеты написал:
как один дубликат переделать

Никак. Их быть не должно.

 

янеты

Пользователь

Сообщений: 21
Регистрация: 21.06.2016

иду по такому пути

Прикрепленные файлы

  • пернос.xlsx (14.45 КБ)

 

Михаил Лебедев

Пользователь

Сообщений: 2838
Регистрация: 17.01.2013

#15

15.04.2017 15:26:45

А где файл с макросом?
М.б. так сработает?

Код
Sub asd() 
' asd Макрос 
 
' здесь строки макроса, потом
    
      x = ("Движение") 'убрать строки со словом "движение"
      For i = Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
      If Cells(i, 2) = x Then Rows(i).Delete
      Nexт
 
 ' продолжение макроса, потом
 
 '     Dim x As Integer  ' добавить пустых строк до 15
          x = Sheets("ЕСТЬ").Range("V7")
          y = Sheets("ЕСТЬ").Range("W7")
          Rows(y).Resize(x).Insert
 
 '  продолжение макроса
       
End Sub

или так?

Код
Sub asd()
 
' asd Макрос 
 
' здесь строки макроса, потом
    
      x = ("Движение") 'убрать строки со словом "движение"
      For i = Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
      If Cells(i, 2) = x Then Rows(i).Delete
      Nexт
 
 ' продолжение макроса, потом
 
 '     Dim x As Integer  ' добавить пустых строк до 15
 '         x = Sheets("ЕСТЬ").Range("V7")
 '         y = Sheets("ЕСТЬ").Range("W7")
          Rows(Sheets("ЕСТЬ").Range("W7")).Resize(Sheets("ЕСТЬ").Range("V7")).Insert
Код
 
 '  продолжение макроса
       
End Sub

или вот так?

Код
Sub asd()
 
' asd Макрос 
 
' здесь строки макроса, потом
    
      x = ("Движение") 'убрать строки со словом "движение"
      For i = Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
      If Cells(i, 2) = x Then Rows(i).Delete
      Nexт
 
 ' продолжение макроса, потом
 
 '     Dim x As Integer  ' добавить пустых строк до 15
 '         x = Sheets("ЕСТЬ").Range("V7")
 '         y = Sheets("ЕСТЬ").Range("W7")
          
with Sheets("ЕСТЬ")
Rows(.Range("W7")).Resize(.Range("V7")).Insert
end with 
 '  продолжение макроса
       
End Sub

Изменено: Михаил Лебедев15.04.2017 15:29:07

Всё сложное — не нужно. Всё нужное — просто /М. Т. Калашников/

 

янеты

Пользователь

Сообщений: 21
Регистрация: 21.06.2016

#16

15.04.2017 16:24:43

УРА!!! Заработало!

Код
Sub asd() 
' asd Макрос 
  
' здесь строки макроса, потом
     
      x = ("Движение") 'убрать строки со словом "движение"
      For i = Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1
      If Cells(i, 2) = x Then Rows(i).Delete
      Nexт
  
 ' продолжение макроса, потом
  
 '     Dim x As Integer  ' добавить пустых строк до 15
          x = Sheets("ЕСТЬ").Range("V7")
          y = Sheets("ЕСТЬ").Range("W7")
          Rows(y).Resize(x).Insert
  
 '  продолжение макроса
        
End Sub

Изменено: янеты15.04.2017 16:39:52

 

RAN

Пользователь

Сообщений: 7081
Регистрация: 21.12.2012

#17

15.04.2017 20:02:19

Михаил Лебедев,
Ответ был очевиден после сообщения №1 и без всяких м.б.
Для вновь ищущего итог — не работало, не работало, заработало! УрЯ!
А зачем, почему, ну никак я не пойму.
И польза от такой темы?
Только в помойку.

I’m trying to gather data from multiple sheets in a selected workbook. I’m using the following code:

Sub Multiplesheet()

Dim filepath As Variant
Dim outputFilePath As String
Dim outputSheetName As String
Dim sql As String
Dim wbk As Workbook, wks As Worksheet
Dim rng As Excel.Range
Dim sheetname As Variant

'To which file and sheet within the file should the output go?
outputFilePath = "C:Usersz003k50sDesktopTestOutput.xlsx"
outputSheetName = "Sheet1"

For Each filepath In Application.GetOpenFilename(FileFilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
    Set schema = conn.OpenSchema(adSchemaTables)
    For Each sheetname In schema.GetRows(, , "TABLE_NAME") 'returns a 2D array of one column
        sql = sql & _
            "UNION ALL SELECT F1 " & _
            "FROM [" & sheetname & "]" & _
                "IN """ & filepath & """ ""Excel 12.0;"""
    Next
Next
sql = Mid(sql, 5) 'Gets rid of the UNION ALL from the first SQL

Dim conn As New ADODB.Connection
Dim rs As ADODB.Recordset
 With conn
    .Provider = "Microsoft.ACE.OLEDB.12.0"
    .ConnectionString = "Data Source=""" & filepath & """;" & _
        "Extended Properties=""Excel 12.0;HDR=No"""
    .Open
    Set rs = .Execute(sql)
    Set wbk = Workbooks.Open(outputFilePath, , True)
    Set wks = wbk.Sheets(outputSheetName)
    wks.Cells(2, 1).CopyFromRecordset rs
    wks.Columns.AutoFill
    .Close
End With

End Sub

When I debug it highlights:

 conn As New ADODB.Connection

I’m very new to Excel VBA and I don’t know what it means.

Community's user avatar

asked Sep 15, 2015 at 12:09

Philip.T's user avatar

4

Snippet of your code:


For Each filepath In Application.GetOpenFilename(FileFilter:="Excel Files (*.xl*), *.xl*", MultiSelect:=True)
'----------
    Set schema = conn.OpenSchema(adSchemaTables) '<~~~ HERE YOU HAVE USED 'conn'
'----------

    For Each sheetname In schema.GetRows(, , "TABLE_NAME") 'returns a 2D array of one column
        sql = sql & _
            "UNION ALL SELECT F1 " & _
            "FROM [" & sheetname & "]" & _
                "IN """ & filepath & """ ""Excel 12.0;"""
    Next
Next
sql = Mid(sql, 5) 'Gets rid of the UNION ALL from the first SQL

'---------
Dim conn As New ADODB.Connection '<~~~ already exists, so duplicate declaration
'---------

Dim rs As ADODB.Recordset
 With conn

As you can see from my comments, you have used conn and then tried to dimension (Dim) it, which is why you are getting the compile error.

answered Sep 15, 2015 at 12:40

SierraOscar's user avatar

SierraOscarSierraOscar

17.4k5 gold badges41 silver badges68 bronze badges

5

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

  • Remove From My Forums
  • Question

  • Dim cl As Range On Error GoTo Whoa Application.EnableEvents = False If Not Intersect(Target, Columns(Range("OrigCost").Column)) Is Nothing Or _ Not Intersect(Target, Columns(Range("DestCost").Column)) Is Nothing Or _ Not Intersect(Target, Columns(Range("RailLineHaulCost").Column)) Is Nothing Or _ Not Intersect(Target, Columns(Range("EqptProgram").Column)) Is Nothing Or _ Not Intersect(Target, Columns(Range("RailFuelCost").Column)) Is Nothing Or _ Not Intersect(Target, Columns(Range("RailEqptCost").Column)) Is Nothing Or _ Not Intersect(Target, Columns(Range("RailEmptyRepoCost").Column)) Is Nothing Or _ Not Intersect(Target, Columns(Range("RailOtherPTCost").Column)) Is Nothing Or _ Not Intersect(Target, Columns(Range("RailPTAdder").Column)) Is Nothing And _ Range("CL6", "CL6").Value = 0 Then ' Range("CL6", "CL6").Value = 0 Then For Each cl In Target.Columns(1) Call calcFirstRound(cl.Row) Next Else MsgBox "mensaje" End If LetsContinue: Application.EnableEvents = True Exit Sub Whoa: MsgBox Err.Description Resume LetsContinue ' Punto 3.1.5 ' 3.1.5 Recalculation from the Cost when the Sell Base or the Pacer RPM has been edited by the user If Not Intersect(Target, Columns(Range("SellBase").Column)) Is Nothing Or _ Not Intersect(Target, Columns(Range("RPM").Column)) Is Nothing _ Then For Each cl In Target.Columns(1) Call calcSecondRound(cl.Row) Next End If LetsContinue: Application.EnableEvents = True Exit Sub Whoa: MsgBox Err.Description Resume LetsContinue End Sub

    regards
      I have thiscodebut whenIrun itthrows the errorof the title
    Where is theerror?

Answers

  • You have two labels named LetsContinue and two labels named Whoa.

    I think the part

        ' Punto 3.1.5
        '  3.1.5   Recalculation from the Cost when the Sell Base or the Pacer RPM has been edited by the user
        If Not Intersect(Target, Columns(Range("SellBase").Column)) Is Nothing Or _
            Not Intersect(Target, Columns(Range("RPM").Column)) Is Nothing _
            Then
            For Each cl In Target.Columns(1)
                Call calcSecondRound(cl.Row)
            Next
        End If

    needs to be moved to above the first LetsContinue, and the second instance of

    LetsContinue:
        Application.EnableEvents = True
        Exit Sub
    Whoa:
        MsgBox Err.Description
        Resume LetsContinue

    should be removed.


    Regards, Hans Vogelaar

    • Marked as answer by

      Wednesday, June 27, 2012 12:03 PM

    • Unmarked as answer by
      palermo_software
      Thursday, July 5, 2012 7:02 PM
    • Marked as answer by
      palermo_software
      Thursday, July 5, 2012 7:02 PM

I just compiled this together it was working fine till i added more ElsIf’s

Error says:
«Compile error: Duplicate declaration in current scope»

Code (pardon it a bit long):
[VBA] Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Const WS_RANGE2 As String = «B216,B419,B622,B825,B1028,B1231,B1434,B1637,B1840,B2043,B2246,B2449,B2652, B2855,B3058,B3261,B3464,B3667,B3870,B4073,B4276,B4479,B4682,B4885,B5088»
Const WS_RANGE1 As String = «B15,B421,B624,B827,B1030,B1233,B1436,B1639,B1842,B2045,B2248,B2451,B2654,B 2857,B3060,B3263,B3466,B3669,B3872,B4075,B4278,B4481,B4684,B4887,B5090»
Const WS_RANGE2 As String = «B17,B220,B626,B829,B1032,B1235,B1438,B1641,B1844,B2047,B2250,B2453,B2656,B 2859,B3062,B3265,B3468,B3671,B3874,B4077,B4280,B4483,B4686,B4889,B5092»
Const WS_RANGE3 As String = «B19,B222,B425,B831,B1034,B1237,B1440,B1643,B1846,B2049,B2252,B2455,B2658,B 2861,B3064,B3267,B3470,B3673,B3876,B4079,B4282,B4485,B4688,B4891,B5094»
Const WS_RANGE3 As String = «B21,B224,B427,B630,B1036,B1239,B1442,B1645,B1848,B2051,B2254,B2457,B2660,B 2863,B3066,B3269,B3472,B3675,B3878,B4081,B4284,B4487,B4690,B4893,B5096»
Const WS_RANGE3 As String = «B23,B226,B429,B632,B835,B1241,B1444,B1647,B1850,B2053,B2256,B2459,B2662,B2 865,B3068,B3271,B3474,B3677,B3880,B4083,B4286,B4489,B4692,B4895,B5098»
Const WS_RANGE3 As String = «B25,B228,B431,B634,B837,B1040,B1446,B1649,B1852,B2055,B2258,B2461,B2664,B2 867,B3070,B3273,B3476,B3679,B3882,B4085,B4288,B4491,B4694,B4897,B5100»
Const WS_RANGE3 As String = «B27,B230,B433,B636,B839,B1042,B1245,B1651,B1854,B2057,B2260,B2463,B2666,B2 869,B3072,B3275,B3478,B3681,B3884,B4087,B4290,B4493,B4696,B4899,B5102»
Const WS_RANGE3 As String = «B29,B232,B435,B638,B841,B1044,B1247,B1450,B1856,B2059,B2262,B2465,B2668,B2 871,B3074,B3277,B3480,B3683,B3886,B4089,B4292,B4495,B4698,B4901,B5104»
Const WS_RANGE3 As String = «B31,B234,B437,B640,B843,B1046,B1249,B1452,B1655,B2061,B2264,B2467,B2670,B2 873,B3076,B3279,B3482,B3685,B3888,B4091,B4294,B4497,B4700,B4903,B5106»
Const WS_RANGE3 As String = «B33,B236,B439,B642,B845,B1048,B1251,B1454,B1657,B1860,B2266,B2469,B2672,B2 875,B3078,B3281,B3484,B3687,B3890,B4093,B4296,B4499,B4702,B4905,B5108»
Const WS_RANGE3 As String = «B35,B238,B441,B644,B847,B1050,B1253,B1456,B1659,B1862,B2065,B2471,B2674,B2 877,B3080,B3283,B3486,B3689,B3892,B4095,B4298,B4501,B4704,B4907,B5110»
Const WS_RANGE3 As String = «B37,B240,B443,B646,B849,B1052,B1255,B1458,B1661,B1864,B2067,B2270,B2676,B2 879,B3082,B3285,B3488,B3691,B3894,B4097,B4300,B4503,B4706,B4909,B5112»
Const WS_RANGE3 As String = «B39,B242,B445,B648,B851,B1054,B1257,B1460,B1663,B1866,B2069,B2272,B2475,B2 881,B3084,B3287,B3490,B3693,B3896,B4099,B4302,B4505,B4708,B4911,B5114»
Const WS_RANGE3 As String = «B41,B244,B447,B650,B853,B1056,B1259,B1462,B1665,B1868,B2071,B2274,B2477,B2 680,B3086,B3289,B3492,B3695,B3898,B4101,B4304,B4507,B4710,B4913,B5116»
Const WS_RANGE3 As String = «B43,B246,B449,B652,B855,B1058,B1261,B1464,B1667,B1870,B2073,B2276,B2479,B2 682,B2885,B3291,B3494,B3697,B3900,B4103,B4306,B4509,B4712,B4915,B5118»
Const WS_RANGE3 As String = «B45,B248,B451,B654,B857,B1060,B1263,B1466,B1669,B1872,B2075,B2278,B2481,B2 684,B2887,B3090,B3496,B3699,B3902,B4105,B4308,B4511,B4714,B4917,B5120»
Const WS_RANGE3 As String = «B47,B250,B453,B656,B859,B1062,B1265,B1468,B1671,B1874,B2077,B2280,B2483,B2 686,B2889,B3092,B3295,B3701,B3904,B4107,B4310,B4513,B4716,B4919,B5122»
Const WS_RANGE3 As String = «B49,B252,B455,B658,B861,B1064,B1267,B1470,B1673,B1876,B2079,B2282,B2485,B2 688,B2891,B3094,B3297,B3500,B3906,B4109,B4312,B4515,B4718,B4921,B5124»
Const WS_RANGE3 As String = «B51,B254,B457,B660,B863,B1066,B1269,B1472,B1675,B1878,B2081,B2284,B2487,B2 690,B2893,B3096,B3299,B3502,B3705,B4111,B4314,B4517,B4720,B4923,B5126»
Const WS_RANGE3 As String = «B53,B256,B459,B662,B865,B1068,B1271,B1474,B1677,B1880,B2083,B2286,B2489,B2 692,B2895,B3098,B3301,B3504,B3707,B3910,B4316,B4519,B4722,B4925,B5128»
Const WS_RANGE3 As String = «B55,B258,B461,B664,B867,B1070,B1273,B1476,B1679,B1882,B2085,B2288,B2491,B2 694,B2897,B3100,B3303,B3506,B3709,B3912,B4115,B4521,B4724,B4927,B5130»
Const WS_RANGE3 As String = «B57,B260,B463,B666,B869,B1072,B1275,B1478,B1681,B1884,B2087,B2290,B2493,B2 696,B2899,B3102,B3305,B3508,B3711,B3914,B4117,B4320,B4726,B4929,B5132»
Const WS_RANGE3 As String = «B59,B262,B465,B668,B871,B1074,B1277,B1480,B1683,B1886,B2089,B2292,B2495,B2 698,B2901,B3104,B3307,B3510,B3713,B3916,B4119,B4322,B4525,B4931,B5134»
Const WS_RANGE3 As String = «B61,B264,B467,B670,B873,B1076,B1279,B1482,B1685,B1888,B2091,B2294,B2497,B2 700,B2903,B3106,B3309,B3512,B3715,B3918,B4121,B4324,B4527,B4730,B5136»
Const WS_RANGE3 As String = «B63,B266,B469,B672,B875,B1078,B1281,B1484,B1687,B1890,B2093,B2296,B2499,B2 702,B2905,B3108,B3311,B3514,B3717,B3920,B4123,B4326,B4529,B4732,B4935»

If Not Intersect(Target, Me.Range(WS_RANGE1)) Is Nothing Then
With Target
Range(«B13»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B218»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B628»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B833»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B1038»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B1243»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B1448»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B1653»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B1858»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B2063»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B2268»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B2473»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B2678»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B2883»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B3088»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B3293»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B3498»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B3703»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B3908»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B4113»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B4318»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B4523»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B4728»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B4933»).Select
End With
ElseIf Not Intersect(Target, Me.Range(WS_RANGE2)) Is Nothing Then
With Target
Range(«B5138»).Select
End With

End If
End Sub[/VBA]

THE VBA help log says:

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: [vba]Sub MySub()
    Dim A As Integer
    Dim A As Variant
    . . . ‘ Other declarations or procedure code here.
    End Sub
    [/vba]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).

I was Referd to this type of code:

[vba]
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
On Error Goto errH
Application.EnableEvents = False
Select Case Target.Address(0, 0)
Case «B15»
Range(«B218»).Select
Case «B17»
Call Range(«B219»).Select ‘<== macro2(target)
Case Else
Goto errH
End Select
errH:
Application.EnableEvents = True
End Sub
[/vba]
but couldnt get it to work

ps. thanks for looking, any ideas love to here um.

  1. 01-14-2017, 02:07 AM


    #1

    JPDutch is offline


    Registered User


    Correcting Compile error: duplicate declaration…

    I am trying to combine two sub macros with a Sub Main() macro, but I get a �Compile error: duplicate declaration in current scope.� I know I have two occurrences of �Dim i� (I think that�s the problem) but I don�t know a work-around. Could anyone offer of a suggestion? The code is as follows:

    Thank you in advance!
    JPDutch


  2. 01-14-2017, 02:28 AM


    #2

    Re: Correcting Compile error: duplicate declaration…

    You’re correct — you can’t define two dimensions (Dim) in the same macro with the same name. The second i dimension isn’t being used at all — delete or comment it out.

    ____________________________________________
    Please ensure you mark your thread as Solved once it is. Click here to see how
    If this post helps, please don’t forget to say thanks by clicking the star icon in the bottom left-hand corner of my post


  3. 01-14-2017, 08:24 AM


    #3

    stimulus is offline


    Registered User


    Re: Correcting Compile error: duplicate declaration…

    You also have two constants called NumCopies.


  4. 01-14-2017, 01:02 PM


    #4

    JPDutch is offline


    Registered User


    Re: Correcting Compile error: duplicate declaration…

    Quote Originally Posted by Trebor76
    View Post

    You’re correct — you can’t define two dimensions (Dim) in the same macro with the same name. The second i dimension isn’t being used at all — delete or comment it out.

    Thanks Treor76, I tried commenting it out, but the «program» didn’t function the way it does when they run separately. My problem is that I don’t know the options to place into the code. For example, if I comment that second i dimension out, it no longer places the correct numbering for all the OSHA logs I’m trying to generate, so when I take out the «dim i as integer» what would I put in its place to keep the correct numbering in place…which is used by the vLookup? I’m sure the answer is staring me in the face, but I’m just not seeing it. Thanks again for your help.


  5. 01-14-2017, 01:13 PM


    #5

    JPDutch is offline


    Registered User


    Re: Correcting Compile error: duplicate declaration…

    Thank you… All the code that I posted was developed over the years by members of this forum helping me out. Some of the items make sense, and I’m trying to learn VBA, but there is so much that still doesn’t make sense to me. For example, I’m still struggling with the work-around for commenting out the «dim i As long» or «dim i As interger.» If I remove either one, the program doesn’t function properly. Thanks again for your help…


  6. 01-14-2017, 05:06 PM


    #6

    Re: Correcting Compile error: duplicate declaration…

    Hi JPDutch

    The Code will not Compile with the Duplicate Declarations and, accordingly, will not run. As Trebor pointed out, Dim i as Integer is not used in the Code.

    You indicate Dim i as Integer is used in the Sub InserYearBranchNumberVLkup2() part of the Code…I don’t see where.

    Bottom line, removing Dim i as Integer appears to have no relationship to this…

    I tried commenting it out, but the «program» didn’t function the way it does when they run separately.

    or this…

    it no longer places the correct numbering for all the OSHA logs I’m trying to generate,

    There’s something else going on. If you wish help troubleshooting you’ll need to attach your File(s).

    John

    If you have issues with Code I’ve provided, I appreciate your feedback.

    In the event Code provided resolves your issue, please mark your Thread as SOLVED.

    If you’re satisfied by any members response to your issue please use the star icon at the lower left of their post.


  7. 01-14-2017, 07:19 PM


    #7

    JPDutch is offline


    Registered User


    Re: Correcting Compile error: duplicate declaration…

    Well, the file has confidential information, so I cannot send it. Allow me to put in the original two macros so you can see it as compared to what I’m hoping to accomplish. I’m trying to create 219 OSHA Logs and Summary pages. The first macro creates the 219 OSHA Log and Summary workbooks (now set to 8 workbooks) and names and saves the file…and it works well. The second macro puts the year in cell A1 and then the first branch number in A4; after that various vlookups pull information into the spreadsheet based on the branch number like injuries, branch addresses, phone numbers etc. to then populate the Log and Summary; this second macro also works well. The problem comes when I try to merge the two into one macro.

    Here’s the second macro I use to populate the OSHA Logs and Summary Pages:

    Combining these two is where the problem comes in, so I’m trying to modify the code to allow everything to run smoothly. Please let me know if you still need the file; if so, I’ll remove the confidential information and then send it to you. Thanks to all who are helping me with this. JPDutch.


  8. 01-14-2017, 07:43 PM


    #8

    Re: Correcting Compile error: duplicate declaration…

    Hi JPDutch

    Well, if what you have truly works for you, don’t combine the Code. Simply ADD the suggested Line of Code to Sub CreateWorkbooks1()


  9. 01-14-2017, 08:56 PM


    #9

    JPDutch is offline


    Registered User


    Re: Correcting Compile error: duplicate declaration…

    I’ll give it shot and get right back with you. Thanks!


  10. 01-14-2017, 09:02 PM


    #10

    JPDutch is offline


    Registered User


    Re: Correcting Compile error: duplicate declaration…

    Superb! It worked like a charm. Thank you so very much! [SOLVED]

    Last edited by JPDutch; 01-14-2017 at 09:04 PM.


  11. 01-14-2017, 09:38 PM


    #11

    Re: Correcting Compile error: duplicate declaration…

    You’re welcome…glad I could help.

    If you’re satisfied by any members response to your issue please use the star icon at the lower left of their post.


Понравилась статья? Поделить с друзьями:
  • Compile error cannot define scripted plugin class
  • Compile error byref argument type mismatch
  • Compile error block if without end if
  • Compile error argument not optional vba
  • Compile error ambiguous name detected