# Incorrect Syntax For Setting Value Of Variable

Nov 26, 2013

I'm not sure where my syntax is wrong, and I can't think of what to google to learn more about the possible options I have when creating and declaring the value of variables.

I am simply trying to define the variable aWB as a workbook, whose name is found in cell B6 on the worksheet named "Start" in the workbook named "DW1". This seems to make sense to me, but I am not typing it correctly.

Code:
Dim aWB As Workbook
Set aWB = Workbooks("DW1.xlsm").Worksheets("Start").Cells("B6").Value

## VBA Function - Incorrect Syntax

Aug 22, 2007

I'm trying to create a new function in Excel and for some reason the syntax is incorrect and it won't let me use it in the sheet. I do not know what I'm doing wrong so any help would be appreciated. This function will allow me to interpolate the term structure of interest rates between dates (I think) My code is

Function INTSPOT(spots, year)
'Interpolates spot rates to year
Dim i As Integer, spotnum As Integer
spotnum = spots.Rows.Count
If Application.WorksheetFunction.Count(spots) = 1 Then
'Single rate given
INTSPOT = spots
Else 'Term structure given
If year = spots(spotnum, 1) Then
INTSPOT = spots(spotnum, 2)
Else
Do
i = i + 1
Loop Until spots(i, 1) > year
INTSPOT = spots(i - 1, 2) + (spots(i, 2) - spots(i - 1, 2)) * _
(year - spots(i - 1, 1)) / _
(spots(i, 1) - spots(i - 1, 1))
End If
End If

End Function

## Syntax Must Be Incorrect For Range Reference

Feb 13, 2010

The following sub to create and name wsheets results naming the new sheet with the value of "A9" only, but what I want to name the new sheet is "A9" + "B9".
Sub CreateWorksheets()
Dim newSheet As Worksheet, itemSheet As Worksheet
Dim cell As Object
Dim itemrange As String

Set itemSheet = Sheets("BIDFORM")

Application.ScreenUpdating = False
itemrange = "A9:B9:" & itemSheet.Range("A9").End(xlDown).Address
For Each cell In itemSheet.Range(itemrange)
If SheetExists(cell.Value) = False Then
Sheets.Add Before:=Sheets("BACK SHEET"), _
Type:="C:PathFile"
Set newSheet = ActiveShee
newSheet.Name = cell.Value
End If
Next cell
Application.ScreenUpdating = True
End Sub

## VB: Incorrect Syntax For Assigning Variables

Jun 3, 2006

I know that I cannot automatically assign UniqueCount the value of that formula. How would I format the line such that I can indeed assign UniqueCount the row value of that line?

## Incorrect Scoping Of Variable?

Mar 1, 2012

I have two pieces of code in module 1 and module 2 respectively:

This code is meant to find the first row number that has a string value of "" in column A:

HTML Code:
Sub Macro1()
Dim cell As Range
Dim r As Double
Dim p As String
For Each cell In Worksheets("stock in").Range("stockcode")
p = cell.Value
r = cell.Row
If p = "" Then Exit For Else
Next cell
End Sub

BTW column A will contain formulas that evaluate to "" so I assume cell.value will = "" even if it contains a formula?

In the second module a sort is executed on the range based on the number of rows:

HTML Code:
Sub Macro2()
'
' Macro2 Macro
'
Call Macro1

ActiveWorkbook.Worksheets("Stock in").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Stock in").Sort.SortFields.Add Key:=Range("A4:A" & r) _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal

[Code] .......

My code is falling down because I think my variables arent scoped right or my code is in the wrong place. Also macro1 will eventually be executed from a button on a different sheet (I dont know if this will matter).

The whole point of this code is to get around the fact that if you perform A - Z sorts on cells that contain formulas those that evaluate to "" will be at the top leaving lots of blank rows before actual visible data.

## Syntax For Variable Array

Aug 11, 2009

I have a variable array, that is, the first cell of the array is variable and the last cell is variable. I have dimmed the first cell , "firstcell" as a range. I have dimmed the last cell , "lastcell" as a range. I'd like to sort the array but first I have to select all cells in the array. Need the proper syntax to select all cells between "firstcell" and "lastcell" in my macro.

## SUMPRODUCT Syntax With Variable VBA

Dec 14, 2009

I need syntax using SUMPRODUCT. I have these two lines of code

## Syntax Correction: Combine Text With Variable

May 8, 2009

I have the following VBA code and try to sum the range from B2 to CY2 for DA2; then B3 to CY3 for DA3, etc. Therefore I use the for loop. It results in "Application defined or Object defined error".

## Correct Syntax To Add Workbook Name That Is Stored In Variable Into Formula?

Feb 24, 2014

I have the following code, which executes just fine:

[Code].....

The problem is that I need to run this again in a different column, and the data is held in another sheet that I have given the variable StepTwo to.

I'm not sure of the syntax to do this. Basically - this is what I need the code to do:

[Code] ....

Understandably this is totally incorrect, but it's the best I can do to explain what I'm actually trying to do....

The two parts of SUMIF are both held in a workbook that I've given the variable "StepTwo" to. Both sets of data are also held on Sheet(1) of that workbook.

## Setting A Global Variable

May 27, 2008

If I want to set a global variable when I open my workbook which will be used in code on the individual spreadsheets, how would I do this? I want to set the time the workbook is opened to a variable (constant) and then compare that time to current time on each calculation in the worksheets.

I'm using Excel 2000.

## Setting Variable For Next Statements?

Sep 3, 2013

I am trying to do the following

Code:
If Range(DataType) = 1 Then
For SubSet = 1 To 3
ElseIf Range(DataType) = 2 Then

[Code]....

Now I realise the code is wrong but what I can do in order to get a variable For statement to work. Or am I just missing the obvious.

## Setting Formula With Variable?

Nov 6, 2013

Trying to Figure out the syntax for setting range properties with a variable. Is this possible?

Code:
Sub Testing()
SomeVariable=7
.Range("B7").Formula="=Average(A & SomeVariable:C & SomeVariable)"
End Sub

## Setting A Variable To A Sheet Name In VB

Apr 27, 2007

How do I set a variable to the active sheet name in VB.

Hypothetical example here:

Dim Sht as Name
Sht = Activesheet.Name

## Setting Variable Names In Vba

Aug 10, 2009

I am working on a macro for excel which has a userform where the user puts in the number of samples they have, then takes them to a new userform to input the weights of the samples. I want to be able to set the sample mass variable dynamically based on the number of samples they have�

i.e.

spl1
spl2
spl3
.
.
.
splx

x=number of samples

This number will be different each time so I am stumped at how to do this since I have just started in vba and do not know too much yet.

## Setting Global Variable From A UserForm

Jul 31, 2009

I have a UserForm that runs when my excel project starts that prompts the user for two pieces of data: a username and a password (these are not for logging into the file itself, I need to use them to call web queries later). I want the UserForm to store both of these data in global variables, so that macros that are run in the future can refer to them and read their values. Unfortunately, I am very new to VBA and I cannot figure out what code I need and where exactly I need to put it. Here is my current code, where "authentication" is the name of the UserForm object, and the textboxes I use for entry are named "user" and "pass": In "This Workbook"

## Setting Variable As Data Range?

Dec 12, 2011

I am attempting to set a variable as a range of data that sits on a non-activated worksheet. However, I am getting a runtime error of 13 (data mismatch).

Is there something in my code that may be incorrect? Here is my code:

Dim rRange As Range
Dim sRange As String
Dim tblName As String

[Code]......

## Setting A Range Using String Variable

Jan 8, 2014

I'm having trouble setting the Range "UtilizationRange" using a variable, "CurrentRange" to store that range. I get the error "Run-Time error 1004: Method 'Range' of object'_Global' failed".The rest of my code works when I set the utilization range using the actual range for my purposes, but the problem is the range will change each month and I don't want to change it manually each time. There's a cell in the excel sheet this refers to (AG3) that holds the range value, which in this case is [N7:N75], and I would just like to return that value to the variable "CurrentRange" and set UtilizationRange equal to that.

The value is returned to CurrentRange, but it's the last line that's giving me the problem.

Sub RangeTest()Dim UtilizationRange As Range, Cell As RangeDim CurrentRange As String
CurrentRange = Range("AG3").Value MsgBox (CurrentRange)
'This returns the value [N7:N75], which is what I want
Set UtilizationRange = Range("CurrentRange")End Sub

## Error Setting Range Variable

Aug 8, 2006

i have compiled a multipage using some borrowed code and some code i have written myself. most of it works, but i have a problem populating listbox2.the error is in Private subCmbFindAllJobNo_Click(). i have put h1 tags around the line of code which shows the error when i debug. this code works ok as a stand alone, so i suspect i have done something wrong in the userform initialise.

Option Explicit
Dim rng As Range
Const FirstRow As Long = 2
Dim r As Long
Dim ans As Variant
Dim MyArray(100, 4)

Public MyData As Range, c, d As Range

Private Sub cmbAmend_Click()

Application. ScreenUpdating = False
Set c = Worksheets("ENTRY SHEET").Range("b4").End(xlUp).Offset(3, 0)
c.Value = Me.DTPicker1.Value
c.Offset(1, 0).Value = Me.TextBox1.Value
c.Offset(2, 0).Value = Me.TextBox2.Value ..........

## Setting A Range Object Variable's Address

Apr 1, 2009

Here is my code

Dim LastCell As Range
Set LastCell = Cells(EndRow, LastCol).Address

I get a "Object Required" when this I try to set the address. I know this is easy.

## Run-Time Error Setting Worksheet Variable

Aug 30, 2007

The user is asked for one piece of information "Enter the ID Number.

What the macro should do then is go to Wks1 find the ID Number and change some cells as a result. This bit works.

Set Wks2 = Worksheets(strWks)

7 rows from the bottom.

My intention was to capture the the name of another worksheet which is held on the same row as the ID Number on Wks1 and call it strWks.

Then further down the macro set the value of Wks2 to that of strWks so that the macro will then go to that sheet and remove data from the row with the same ID Number.

I get a Time Run Error 9.

It just seems to be the bit at the bottom where I am trying to identify Wks2 using strWks.

Sub Macro01C_Auto_Resign()
Dim Wks1 As Worksheet, Wks2 As Worksheet
Dim strFind As String, rngFound As Range
Dim lngRow As Long, rngUnion As Range, strWks As String ............................

## Setting Column Chart Data Using VBA For Variable Ranges

Mar 10, 2014

I have some code to plot a column chart of data but it isn't working as expecting at the moment. The code is below. The variable binCounter is a count of how many cells in a range that I want to plot on the chart.

However, what I am finding is that the first couple of cells in the range appear as the series name with the rest appearing as the data in the chart. Secondly, the chart appears with the axis labels 1,2,3 etc when I have some custom ones I would prefer to use. How do I go about setting this property, as I can only find options on setting the axis title There is a lot of stuff on XY charts on Google but I can't find much on column charts unfortunately .

VB:
'activate sheet and chart
ActiveSheet.ChartObjects("Histogram").Activate

'set variables for chart
With ActiveChart

[Code] .....

## Setting Variable, Discontinuous Print Area In A Macro

May 29, 2009

I need to write a macro to set the print area to the first two columns (A & B), and the last 12 columns (the last column may change). In both cases I need to print all rows (start is row 1, last row is variable). I am trying to achieve something like the "Freeze Pane" effect with the printer. The first two rows contain column headers (dates). The first two columns contain information that needs to be included on the printout, whilst the last 12 columns contain the most recent data.
Various cells withing the selected ranges may be blank, but no row or column will be entirely blank.

## Invalid Qualifer Error -setting Variable Using Getpivotdata

Mar 22, 2007

We have a very long macro that at the end sends an email to each training coordinator. Within the body of the email, we want to autopopulate the completion status from a pivot table using getpivotdata.

We first try to set the variable but get an error: [compile error:invalid qualifier].

Sheets(Summary).Select
Dim BDCompletion As String
BDCompletion = Application.PivotTableSelection.GetPivotData(A3, "Business Dev Plan Found")

And this is how we plan to incorporate the variable into the body of the email:

With OutMail
.To = "name@company.com"
.CC = ""
.BCC = ""
.Subject = CurrentSheet.Name & " Training Plan Status as of " & Format(Now, "dd-mmm-yy")
.Body = "BD is " & BDCompletion & " complete for 2007 Training Plans as of the date of this email."
'You can add other files also like this
.Send 'or use .Display
End With

## Setting Values In A Variable Range Occurence Query

Jul 18, 2006

I am trying to count the occurences of combinations within a range defined by contiguous cell values in one column. My problem lies with setting the value of variables that are queried within the defined range. My macro should;

1)Set ComboValue1 & ComboValue2 values to A1 & B1 cells values respectively
2)define range to be searched by how many contiguous values there are in column D
3)search column E for 2 figure combination (defined by A1 & B1). If present increment counter by 1 and add to column C (to be visible in worksheet). If no match carry on
4)define new range by next set of contiguous values in column C
5) step 3
6)when all possible contiguous ranges defined and searched from column c, perform again on next combination down columns A & B with refreshed occurence counter
7)finish when all combinations are searched for

Sub CountComboOccurence()
Dim ListCounter As String
Dim ProgCounter As String
Dim Counter As Integer
Dim ComboValue1 As String
Dim ComboValue2 As String
Dim Rng As Range
Application. ScreenUpdating = False
ListCounter = 0
ProgCounter = 0
Counter = 0
ComboValue1 = 0.......................

## Subcript Out Of Range Error Setting Worksheet Variable

Sep 13, 2006

Subcript Out Of Range Error Coming Now For The Code Which Works For Me Before

Sub WHideRows()

Dim rRange As Range, rCell As Range
Dim strVal As String

Set rRange = Worksheets("WIED PROBLEM WELLS").Range("A11:A110")

For Each rCell In rRange
strVal = rCell(1, 3) & rCell(1, 4) & rCell(1, 5) & rCell(1, 6) & rCell(1, 7) & rCell(1, 9)
rCell.EntireRow.Hidden = strVal = vbNullString
Next rCell

End Sub

i am using the code above to hide the rows which doesn't have any values in all the following Cells 3,4,5,6,7 & 9 or Unhide the rows if there is value in any 1 of the following cells 3,4,5,6,7 & 9 from row number A11 to A110.

The same code works for me before. But now the code is not working. It says below the error message

Run-time error '9':..................

## Object Required Error Setting Range Variable

Aug 22, 2007

code is getting an error on the bold line below. My error message is run time error 424 - object required.....

## Excel 2002 :: Setting Variable To Select All Worksheets In Workbook

Jan 20, 2012

I've got some code which some one posted me a link to on here which set up a pivot table on more that 1 sheets (using excel 2002).

I inserted this code into a rountine I do daily which works fine.

The problem Im having is that Im getting more and more info which I need to pivot over more than one sheet. So I was going to amend the rountine so It picked what ever sheets are in the work book to pivot.

At the moment I have to go into the code and name the sheets to pivot. Is there some code which can work out how many sheets that need pivoting and just do it with out naming them? and also just add a new sheet with the pivot on rather than having to name the destination?

I've posted the code i got given below and have highlighted the bit where I have to name the sheets.

Code:
'---------------------------------------------------------------------------------------
' Procedure : CreateConnection
' Author : KL (Kirill Lapin)
' Date : 18/08/2009

[Code]....

## If Else Syntax: Change Some Outputs Of The Macro Without Changing The Syntax

Jul 19, 2006

I�m writting a macro. It works find until a certain point. When I want to change some outputs of the macro without changing the syntax, it display an error mesage while runing the macro. It says Else without If. Which is quite disturbing because the Else was not creating any problem before. Here is my macro before I changed the conditions (this one work nicely)

Sub Copy_Sheet_Beta()
Set wba = ActiveWorkbook
On Error Resume Next
If IsWorkbookOpened("Projekt.xls", "C:Documents and SettingsfrederikSkrivebordRedd Barna") Then
Workbooks("Projekt.xls").Activate 'In case open, just activate "Projekt"
Else
Workbooks.Open Filename:="C:Documents and SettingsfrederikSkrivebordRedd Barnaprojekt.xls"
End If
Set wb = Workbooks("Projekt.xls")
wb.Activate
If Not SheetExists(wba.ActiveSheet. Range("C1").Value) Then
MsgBox "overall doesn't exist!"
Else........................................

## Wildcard Incorrect

Dec 7, 2007

I have tried everything I can think of to get this to work.

I am searching column B for anything containing "Tease", then if found, look to see if column J contains a "W".

Excel doesn't report an error, but this doesn't work:

=SUMPRODUCT((B3:B40="*Tease*")*(J3:J40="W"))

## IF, AND, OR - Returns Incorrect Value

Apr 29, 2009

I am having problems with the following formular in that it does not return what I am expecting.

I have 2 columns of data that hold Y/N values and I would like either "Yes" or "No" to be displayed in Col C for the 4 possible combinations that the interaction of Y and N in columns A&B give.

The data is
Col A:A = Y or N
Col B:B =Y or N

The four possible combinations and outcomes are:
Col A = Y & Col B = Y outcome in Col C = "Yes"
Col A = N & Col B = Y outcome in Col C = "Yes"

Col A = N & Col B = N outcome in Col C = "No"
Col A = Y & Col B = N outcome in Col C = "No"

The formular I have tried is:
=IF(OR(AND(A1="Y",B1="Y"),A1="N",B1="Y"),"Yes","No")

However while three of the outcomes for the combinations are correct (N/Y, Y/N, Y/Y), the output for the N/N combination is incorrect and returns "Yes" instead of "No".

Just wondering if anyone has any ideas as to what is wrong with this?