View Single Post
  #3   Report Post  
Posted to microsoft.public.excel.programming
J.E. McGimpsey J.E. McGimpsey is offline
external usenet poster
 
Posts: 493
Default Linking VBA code to spreadsheet

VBA can "pick up" and "put back" spreadsheet data in several ways. A
few among them:

You can refer to the cells directly:

Sheets("Sheet1").Range("B7").Value = _
Sheets("Sheet1").Range("B1") + Sheets("Sheet1").Range("B2")

which can be shortened to

With Sheets("Sheet1")
.Range("B7").Value = .Range("B1").Value + .Range("B2").Value
End With

or, if Sheet1 is the activesheet, just

Range("B7").Value = Range("B1").Value + Range("B2").Value

You can assign intermediate variables:

Dim myVar1 As Double
Dim myVar2 As Double
Dim myVar3 As Double

myVar1 = Sheets("Sheet1").Range("B1")
myVar2 = Sheets("Sheet1").Range("B2")
myVar3 = myVar1 + myVar2
Sheets("Sheet1").Range("B7").Value = myVar3

You can assign object variables to refer to the cells:

Dim myCell1 As Range
Dim myCell2 As Range
Dim myCell3 As Range
Set myCell1 = Sheets("Sheet1").Range("B1")
Set myCell2 = Sheets("Sheet1").Range("B2")
Set myCell3 = Sheets("Sheet1").Range("B7")
myCell3.Value = myCell1.Value + myCell2.Value

You can also capture a contiguous range of data into a Variant
variable with a 2-D array:

Dim myRng As Variant
myRng = Sheets("Sheet1").Range("B1:B6").Value
Sheets("Sheet1").Range("B7").Value = _
myRng(1, 1) + myRng(2, 1) - myRng(6, 1)

In article ,
mark_varney47 wrote:

That really does not help me that much ,unfortunately.I already have the
vba code to do the calculations.What I need to know is how I can get
this code to pick up values from an Excel spreadsheet.The input data
would be in cells,B1,B2,B3,B4,B5 and B6.The vba code would take this
data and produce a single result to cell B7.How do I get vba to pick up
this data in the spreadsheet and then put the result back in the
spreadsheet in cell B7.I know that it is a simple question,but I am
stuck and not making much progress.Is there a specific method of
linking a spreadsheet to code in the code editor??