简体   繁体   中英

VBA Excel set variable to row number with .row

I have a lot of files and want to find the areas under portions of the curve. I define how many curves, the X1 and X2.

The macro then finds the row x1 and x2 and then should give me the row number that they are contained in, but I keep getting an error at this step.

Then later on it uses these values to calcultae the area.

It worked once, I made a change to a variable and have never gotten it to work right since.

Here is the code:

Sub Macro1()

Dim myRange, TotalPeak, TotalBack, FoundCell_1, FoundCell_2, J, FileNumber, Point_1, Point_2, CPoint_1, CPoint_2

FileNumber = InputBox("Number of curves")
Point_1 = InputBox("Enter point one of curve")
Point_2 = InputBox("Enter point two of curve")

For J = 1 To FileNumber

FoundCell_1 = ActiveSheet.Columns(1).Find(What:=Point_1, LookIn:=xlValues, LookAt:=xlPart)
FoundCell_2 = ActiveSheet.Columns(1).Find(What:=Point_2, LookIn:=xlValues, LookAt:=xlPart)

CPoint_1 = FoundCell_1.Row
CPoint_2 = FoundCell_2.Row

myRange = ActiveSheet.Range(Cells(CPoint_1, J + 1), Cells(CPoint_2, J + 1))
TotalPeak = Application.WorksheetFunction.Sum(myRange)
TotalBack = ((Cells(CPoint_1, J + 1) + Cells(CPoint_2, J + 1)) / 2) * Abs((CPoint_2 - CPoint_1))
Worksheets("Sheet2").Cells(J, 1) = TotalPeak - TotalBack

Next

End Sub

You need to Set the lines below, since they are to be a range variable, and a range is an object.

Change this:

FoundCell_1 = ActiveSheet.Columns(1).Find(What:=Point_1, LookIn:=xlValues, LookAt:=xlPart)
FoundCell_2 = ActiveSheet.Columns(1).Find(What:=Point_2, LookIn:=xlValues, LookAt:=xlPart)

To:

Set FoundCell_1 = ActiveSheet.Columns(1).Find(What:=Point_1, LookIn:=xlValues, LookAt:=xlPart)
Set FoundCell_2 = ActiveSheet.Columns(1).Find(What:=Point_2, LookIn:=xlValues, LookAt:=xlPart)

This change will allow for the .Row property to be pulled from your range object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM