Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

excel - Using a variable for row in (row,column) for a range in VBA

I have a global variable called processRowBegin that contains the row number for the beginning of a process. I also have a global variable called processRowEnd that contains the row number for the end of a process.

What I am trying to do is create a chart for two columns, Columns C and E on the active worksheet, where the range for the selected rows to be plotted is from processRowBegin to processRowEnd. The problem that I am coming across is that I do not know how to use a range with a variable for the row in (row, column) syntax. I have researched this question and so far have not found a solution that works. I tried using the (row,column) syntax at first with the variable names for the row in (row, column). This did not work and resulted in the error in the picture [Using variable for row in range error][1}.

I then tried to implement a solution (code below) that I found via another user's question but still receive the same error. How does one go about doing this in VBA?

Range(("C" & processRowBegin):("C" & processRowEnd)).Select
Range(("E" & processRowBegin):("E" & processRowEnd)).Select

I am a beginner in Excel VBA as well as programming and would appreciate help. This is my last step to complete an important work project. If anyone would like to view my entire code, please let me know.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would do it this way:

Range("C" & processRowBegin & ":C" & processRowEnd).Select

Range takes either two cells or a string to denote the extents.

To do it by the two cells:

Range(Cells(processRowBegin,3),Cells(processRowEnd,3)).Select

A couple notes:

  1. One should avoid using select and simply do what is desired with the cells. For more information on how to avoid it see this POST

  2. One should always qualify all all range objects to their parent sheets. If using the Cells() they too need to be qualified

Example

With WorkSheets("Sheet1")
    .Range(.Cells(processRowBegin,3),.Cells(processRowEnd,3)).Value = .Range(.Cells(processRowBegin,5),.Cells(processRowEnd,5)).Value
End With

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...