简体   繁体   中英

Excel VBA Cell will not activate

When I run my code it says I am using the correct cell (through my variables), but it does not activate the cell or input my variable value into the cell.

myColumnNumber = 1
Range(myColumnNumber & currentRow1).Activate

Range(myColumnNumber & currentRow1) = FirstName & LastName

myColumnNumber = myColumnNumber + 1
Range(myColumnNumber & currentRow1) = AccNumber
myColumnNumber = myColumnNumber + 1
Range(myColumnNumber & currentRow1) = AccName

My variables all show the correct values when running, but the sheet does not change. For example, if I put Range("a1").Activate for the Active Sheet I can see when that cell activates, but my variables do not affect the change in position.

MyColumnNumner steps through adding "1" and my Current row stays at 2, as it should, but on the sheet there is no change. Can you see any errors in this snip, or is more information required? thank you for any assistance.

Generally speaking, never use .Activate or .Select if you can avoid it. Your code can be reproduced as a one-liner:

Cells(currentRow1, myColumnNumber).Resize(, 3).Value = Array(FirstName & LastName, AccNumber, AccName)

As a side note, you are trying to use Range("Address") but are giving it a number as the column, so use Cells instead of Range (as shown in my provided code).

What I mean by that is, the Range method takes column letters, like Range("A1") or Range("C3") . You are giving it numbers, so it looks like this Range("11") which isn't a valid range. I'm kind of surprised you're not getting an error.

The Cells method, however, takes column numbers or column letters. Cells(rownumber, columnnumber) which is how you should be referencing the appropriate cell, based on the provided code.

Range(myColumnNumber & currentRow1) should reference the range in your workbook.

try adding a range object instead of using Range to reference.

dim rng as Range
set rng = Activeworksheet.Cells

myColumnNumber = 1 
rng (myColumnNumber & currentRow1).Activate
rng (myColumnNumber & currentRow1) = FirstName & LastName

myColumnNumber = myColumnNumber + 1
rng (myColumnNumber & currentRow1) = AccNumber
myColumnNumber = myColumnNumber + 1
rng (myColumnNumber & currentRow1) = AccName 
myColumnNumber = "A"
Range(myColumnNumber & currentRow1).Activate 'No Use

Range(myColumnNumber & currentRow1).Value = FirstName & LastName

' myColumnNumber = myColumnNumber + 1   Error
'The Offset property is the one that you will use the most with Range to move around
'the 'sheet.                  

Range(myColumnNumber & currentRow1).Offset(0,1).Value = AccNumber
Range(myColumnNumber & currentRow1).Offset(0,2).Value = AccName

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