Error: Duplicate Declaration In Current Scope
Jun 28, 2009I get an error: Duplicate declaration in current scope? The formula calculates the compound annual growth rate.
View 5 RepliesI get an error: Duplicate declaration in current scope? The formula calculates the compound annual growth rate.
View 5 RepliesI have the following code which performs the same action on 2 different tabs within the same workbook:
Dim Rng As Range, Dn As Range
Set Rng = Range(Range("O1"), Range("O" & Rows.Count).End(xlUp))
Rng.NumberFormat = "@"
For Each Dn In Rng
If Len(Dn) < 7 Then Dn = String(7 - Len(Dn), "0") & Dn
Next Dn
i get the following error:
Compile Error: Duplicate declaration in current scope
I am trying to automate the creation of 3 pivot tables. At first I was having a problem with deselecting all items in the drop-down except one, then I found the code to fix it.
I replaced this code:
ActiveSheet.PivotTables("PivotTable15").PivotFields( _
"Beta")
.PivotItems("Escalated").Visible = False
.PivotItems("Hang Up").Visible = False
.PivotItems("New Hire Requests").Visible = False
.PivotItems("No Trouble Found").Visible = False
.PivotItems("Priority Exchange").Visible = False
[code].....
This fixed the problem, but there are still two other pivot tables that need to be created after this first one. I scrolled down through the code and deleted the other code blocks for the selection of the PivotItems and replaced it with the code above, but then when I ran it I got the "Compile Error: Duplicate Declaration in current scope".
I read more through the forum and realize that it's because VBA is dimensioning it twice, and I read that you're supposed to Dimension at the beginning of your program, but how do I implement this into my coding?
I can't dimension literally at the start of the code, there is some formatting that needs to take place first. (Basically I paste in a bunch of data into Sheet1 of my workbook, center it, space it out, then insert a pivot table into the pre-existing Sheet2 based on that data, filtered on the blank entries in Column N. Then I need to create ANOTHER pivot table based on that same data in Sheet1, but filtered on the blank entries in Column O. Then I center the words in the Pivot tables' headers in Sheet2, and finally I need to create one last pivot table on pre-existing Sheet3 based on the data on Sheet1, filtered for 2 specific entry types in Column N.)
I am trying to run a VB script that will copy data from 3 worksheets and past it into 3 New worksheets, sort that data into alpha order then delete all rows containing Zeros that may be found in Column B, Then copy that data from the 3 New worksheet back into the original 3 worksheets.
The copying and sorting of the data from one sheet to another is easy. The problem is trying to delete the zeros found in column B once its been copied over into the 3 New worksheets.
The script I am using to delete any Zeros found in Column B is below.
If I try to use this script more then once, so that I can delete all the zeros found in column B on all the New worksheets I get this error “Duplicate declaration in current script”
Is there a way for me to refer back to this script instead of me trying to past it more then once within the VB script.
Application. ScreenUpdating = False
Application.Calculation = xlCalculationManual
Const StartRow As Long = 1 'Row to Start looking at
Dim StopRow As Long
Dim Col As Long
Col = ActiveCell.Column
StopRow = Cells(Rows.Count, Col).End(xlUp).Row
Dim cnt As Long
For cnt = StopRow To StartRow Step -1
If Not IsEmpty(Cells(cnt, Col)) Then
If IsNumeric(Cells(cnt, Col)) Then
If Cells(cnt, Col) = 0 Then Rows(cnt).Delete
End If
End If
Next cnt
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Please see attached workbook. You will understand it better once you see the workbook and the VB script in it.
I am getting "Duplicate Declaration" error while running my code. Cant post entire code as its too long but i am pasting the problem line.
View 12 Replies View RelatedI have a spreadsheet to track events (servicing, repairs, fuelling, etc) for my car - dates in Col A, events in B, mileage in C, prices in D.
I want to return the mileage when the next service is due, based on the mileage of the last service. Using VLOOKUP set to FALSE returns the first service mileage; set to TRUE, it returns random values. The events in Col B repeat in a random order (e.g. fuel, fuel, service, fuel, repairs, fuel, fuel, service).
I have only recently started to learn VBA and have been putting it to practice in creating userforms to help people at my work to be able to timetable more quickly.
I have realised however that in many cases the basic code that I have been using could often be improved. However in the sections below I have not been able to work this out for myself. This needs to be done as after a large number of worksheets exists excel gradually gets slower and slower when running the macros.
If you do what is correct in the program it works fine but if you select the tab saying add client and you getr duplicate sheet it gets a error.
I would like to stop the code and reset the form.
Then if someone could look at the new client tab on whether I could automatically let it add The hyperlink to the sheet for that specific client.
The following is not working for me with an overflow #6 error.
Sub multiplythis()
Dim highnumber ' As Long, I've tried Double, Long and now Variant
highnumber = 50 * 250 * 300 * 400 * 20
End Sub
I've been asked to produce a spread sheet that will calculate split payments for a list of households built by our company. The bill amount will be given to us by the power company, and the basis for bill separation is base on the billing period, and the date of house settlement.
The codes I've produced are written below, however I couldn't get it to run properly. The software keeps on telling me that my variables aren't declared correctly.
I've attached all my codes below for your reference.
Public Start_Date As Date
Start_Date = Worksheets("Sheet_Input").Cells("D", 1).Value
Public End_Date As Date
End_Date = Worksheets("Sheet_Input").Cells("F", 1).Value
Public Total_Date As Integer
Total_Date = Worksheets("Sheet_Input").Cells("H", 1).Value
Public aAverage As Integer
aAverage = Worksheets("Sheet_Input").Cells("B", 3).Value
Public bAverage As Integer
bAverage = Worksheets("Sheet_Input").Cells("D", 3).Value
I'm using a public declaration for a worksheet but I seem to have to initialize it in each routine. Is there a way to set it and leave it? So in a module I have:
View 4 Replies View RelatedI have some code that runs a mouse event and keeps my computer active when I'm away. It works on my 32-bit computer, but doesn't work on my 64-bit. What is the correct syntax to have it work on a 64-bit?
I get the error: "declare stmts must be updated for 64 bit and marked with PtrSafe attribute."
BTW, I already tried changing "user32" to "user64", that didn't work.
Code follows:
Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long
Public Declare Sub mouse_event Lib "user32" (ByVal dwFlags As Long, ByVal dx As Long, ByVal dy As Long, ByVal cButtons As Long, ByVal dwExtraInfo As Long)
Public Const MOUSEEVENTF_LEFTDOWN = &H2
Public Const MOUSEEVENTF_LEFTUP = &H4
Dim TimerActive As Boolean
Sub KeepWindowsActive()
[code].....
using win 7.
I have two issues in SumProduct formula.
1.Formula Def.Cells(c, d).Formula = "=SUMPRODUCT(--(Severity =" & """" & severity_3 & """" & "),
--(OFFSET(Severity,0,4)=" & """" & module & """" & "))"
Where severity_3= Shipping
There are many fields like Shipping, Shipping-UI, Shipping-BE.
I want the formula to consider all the above when severity_3= Shipping and take the count & not only consider Shipping(Shipping*) .
2.Formula test = "0 - Unclassified" Or "Alpha Testing" Or "Beta Testing" Or "Functional - Interface" Or "Functional - Report" Or "Regression Testing" Or "Requirement Review"
when i use the above formula , it is displaying the message "Run-time error'13':Type mismatch There are spaces in the criteria i have used but i am not sure how to resolve this
I suspect the array variables declaration in the following example is the problem.
The array Function MyRoots() incorrectly returns 0.0 results to cells I11:J13.
cell B8::3
cell B9: myTrue
cells B11:C14 numerical values
cells I11:J13:: array function {=MyRoots(B11:C14, B8, B9)}
Function MyRoots (a, m As Integer, polish As String)
ReDim a(m + 1, 2) As Double
ReDim roots(m, 2) As Double
Dim j As Integer, its As Integer
Dim x(2) As Double
ReDim ad(m + 1, 2) As Double
......................................my code............
For j = 1 To m + 1
ad(j, 1) = a(j, 1)
ad(j, 2) = a(j, 2)
Next j
......................................my code............
Call Laguer (ad, j, x, its)
......................................my code............
roots(j, 1) = x(1)
roots(j, 2) = x(2)
......................................my code............
MyRoots = roots
End Function
Sub Laguer (a, m, x, its)
Dim x1(2) As Double
......................................my code.......................................
x(1) = x1(1)
x(2) = x1(2)
......................................my code............
Exit Sub
End Sub
I have a smattering of experience within various programming languages, but am still coming to terms with the basics of VBA. I am trying to declare a global variable, assign it a value, then use that global variable. Within 'ThisWorkbook' I have the following...
Public myText As String
Private Sub Workbook_Open()
myText = "Hi There"
End Sub
...and in the Microsoft Worksheet Object Sheet1 (Sheet1) I have...
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
MsgBox myText
End Sub
Now, my understanding of this code is that upon opening the workbook, myText variable will be declared, and then assigned the value "Hi There". Then, once I have clicked anywhere on Sheet1, a message box will appear stating "Hi There". Problem is, the message box is blank. This is all fine, except I want the message box to state "Hi There". What am I doing wrong? Is the variable declared (publically) correctly? Am I assigning the public variable the value correctly?
Am I referencing the public variable correctly in the Worksheet_SelectionChange procedure correctly?
Just starting with excell and am working on a project for my class. I cannot figure out why the value of the variable "changer" defined by command buttons on sheet1 are not being passed to the procedure contained in command button on sheet 2.
I declared the variable in the general declarations section of sheet1 with
Public changer As Integer
The command buttons on sheet 1 contain
Private Sub CommandButton1_Click()
changer = 1
Cells(1, 1) = changer
End Sub
Private Sub CommandButton2_Click()
changer = 2
Cells(1, 1) = changer
End Sub
The command button on sheet2 contains
Private Sub CommandButton1_Click()
Cells(1, 1) = changer
End Sub
When I click on the command button on sheet2 nothing happens.
What does the term variable scope mean?
View 3 Replies View RelatedI have a formula that hides rows within a range for a sheet.
View 2 Replies View RelatedI am using the format of using variables for declaring file paths and document names in VBA however I want to make sure I am doing it properly...
Dim Server, VersionName As String
Server = Worksheets("Calculation Matrix").Range("CalculationMatrix_Server").Value
VersionName = Worksheets("Calculation Matrix").Range("CalculationMatrix_VersionName").Value
ActiveWorkbook.SaveAs Filename:="" & Server & "uploadcomplete" & VersionName & "", FileFormat:=xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False, CreateBackup:=False
Should these variables be declared as String?
Hopefully this isn't too vague, but almost every project I've worked on so far has not recognized Public variables in all modules. I've constantly been searching for exceptions to this rule that could be contributing to this issue but haven't been successful.
I have read a million times that declaring a variable as Public makes it visible to all modules and preserves the value throughout. I've also read that if you edit code or reset your project, the values may be lost. I also know that if you try to use a variable before you give it a value (or for object variables set it = to something), it doesn't have a value yet. But all this applied, I'm still not getting Public variables to be consistently recognized or stay with the value I want them to have throughout the lifetime of my project (while the workbook is open)
My specific current issue (one of many so far) is that I have 4 command buttons within a worksheet object. Each triggers a different group of procedures, some of these are user forms. In the first button, I create two worksheets one to contain the current fiscal period "Options" the other for "Summary" of all the totals etc... (all financial data). In this first userform, triggered by the button, I allow the user to name these worksheets: like Summer2007Options or Summer2007Summary and I declare these publically as object variables OptSheet and SumSheet. These variable names and sheets are recognized for the next 2 buttons but now that I'm on the fourth, I have object variable not set errors when I try to refer to this variable.
In cell C34 I'm trying to duplicate the content in cell J70, but I don't want to show any content in C34 unless J70 is not blank.
I tried this formula in C34, but I keep receiving an error message:
=if(j70="","",(=j70)
How to prevent a variable holding a pointer to an object from going out of scope and releasing the object pointer after the VB project is reset due to a runtime error during code execution or due to manually resetting the vb project ?
Hooking the Application events in a class module is a scenario where this could be particularly useful - For example, let's assume the application events are hooked upon opening the workbook . Now if the variables go out of scope the application events are no longer functioning which is what i am trying to avoid.
I did once worked around this by creating a VBS script on the fly and continually monitoring the state of the variable from outside excel but this approach has proven problematic on some machines where running scripts is restricted.
I thought about writing an activeX dll in VB6 , loading it in the excel process and hook the application events from there but I don't think this would work because the dll shares the same memory space as the host process.
I have a few lines of code as follows:
Private Sub Workbook_Open()
fileName = ThisWorkbook. Name
fileLocation = ThisWorkbook.Path
Dim strFound As Boolean, pos As Long
If Not fileName = "" Then
strFound = False
pos = 1
Do While strFound = False
stringFound = Mid(fileName, pos, 1)
If stringFound = "-" Then
productName = Mid(fileName, 1, pos - 1)
MsgBox "Name of Product Is: " & productName
strFound = True
Else
pos = pos + 1
End If
Loop
End If
End Sub
It would return "Test" if the file's name is "Test-Part1.xls". I then declare the productName variable as Public (Public productName As String) in one of the modules. But the productName only holds the value for a certain amount of time. After a while, it's empty.
I am trying to create a primitive counter. My idea is to write a value to a file, read it, add one and write it back. The file as a single value tab-delimted of 5000. The code below produces the odd output on debug. I really cant understand it.
Public Function nextInv() As Integer
Dim fname As String
Dim fnum As Integer
Dim stringArray()
Dim invNum As Integer
fnum = FreeFile()
fname = "nextInv.txt"
stringArray() = parse(OpenRecordClassesFn(fname), vbTab)
For i = UBound(stringArray) + 1 To LBound(stringArray)
invNum = stringArray(i)
Next
If FileExists(fname) Then
Open fname For Output As #fnum
End If
invNum = invNum + 1
Debug.Print "invNum"
Print #fnum, (invNum & vbTab)
Close #fnum
invNum = invNum + 1
End Function
Public Sub testHarness()
Debug.Print nextInv()
End Sub
with a output of
5000
invNum
0
and the value in the file of 1. It should be 5001.
I was given a workbook with several bugs and asked to fix it and make it functional again. I was able to fix everything except for a runtime error 1004. On the debug it highlights the following code:
Code:
Private Sub ComboBox1_Change()
End Sub
Private Sub Worksheet_Activate()
LoadSheetNames "Compare_Session_Start", "Engineer*"
End Sub
Private Sub LoadSheetNames(strRangeForValidation As String, strDesiredCodeName As String)
[code]....
Anytime you select the base worksheet or a duplicate it shows the runtime error...
I'm trying to find definitions/commands to make excel find the best combinations of several defined scopes and restrictions to make an output number as high as possible.
This is by using a combination of several different equations, maybe excel has a magic trick for all the variables and formulas.
Attached File: forum_heatexchanger.xlsx‎
It's some code I found and altered that automatically updates the cell to the right of a column that has drop down box data validation, creating a list of the selected values seperated by commas. The thing is, I only want it to do this in columns 8 and 10 but data validation drop-down boxes have been used in several other columns. I've tried various methods of limiting the scope, the latest being the line: If Target.Column = 8 Or 10 Then. But the auto update is still being applied to all drop down boxes in the sheet. So, how can I make sure the auto update only happens when the drop down boxes in columns 8 and 10, updating into columns 9 and 11.
View 4 Replies View Relatedabout variable lifetime/scope in a workbook. Basically I have a Class Module that I set up in the Workbook_Open() event as follows:
Private Sub Workbook_Open()
Set CurrentClient = New CClient
End Sub
Once the workbook is open the user can select their "client" and all properties/methods for that "client" are available throughout the workbook until they close it, and it all works fine. However, whilst developing I'm obviously making lots of changes to the code, and every time I do the object is no longer available in memory.
I've tried manually running the Workbook_Open event after I make a code change, and even put in a button with the same code, but whatever I do the object won't remain in memory until I close & reopen the workbook. It's so frustrating having to close & reopen the whole workbook every time I want to test a code change I've made!
I have two numbers I need to compare using and IF statement. The two numbers are virtually the same, and I want the IF statement to round the numbers so any difference under 100,000 is not detected. For example:
Cell A1 = $32,194,884.45
Cell B1 = $32,194,884.37
I would like the statement to look at this number as 32.19 (divided by 1M). I am using the below equation currently, but it is not working:
=IF(ROUND(A1/1000000,1)<>ROUND(B1/1000000,1),"CHECK","0")
I have a spreadsheet and I’m trying to create several different staffing scenarios
Basically what I want is to populate column E with the amount of staffing based on the number of classes in column B. The range that I want to apply is in the green box in the sample. I’m trying to have excel give me the staffing value if the current number in cell B5 is a certain value – so in the example 1 through 4 = .2, 5 through 8 = .4 and 9 through 12 = .6. this site gave me some ideas so I tried V lookup and Index but I seem to be missing something and wonder if it is not combinations of nested functions?