1

I can't seem to get something so simple to work in excel VBA

I have data on cell A1

Sub TestBox()
ActiveSheet.Activate
MsgBox (Cells(0, 0).Value)
End Sub

I want to output said data using basically a msgBox

Run-time error:'1004' Application -defined or object-defined error

5
  • Unrelated to your problem, but why do you use ActiveSheet.Activate? By definition, the ActiveSheet is the one that is active, so that seems to be a pointless piece of code. Commented Aug 2, 2017 at 21:19
  • I have no idea I guess i wanted to be implicit in describing which sheet I was using Commented Aug 2, 2017 at 21:22
  • 1
    If you want to be explicit in defining which sheet you are using, you should start your code with something like Dim ws As Worksheet: Set ws = ActiveSheet and then use MsgBox ws.Cells(1, 1).Value. If you don't, the user could change the active sheet between when you set the active sheet to be the active sheet and when the MsgBox is displayed. Commented Aug 2, 2017 at 21:25
  • Possible duplicate of Error for using cells() for string in vba? Commented Aug 2, 2017 at 21:42
  • I meant *explicit. I will start using this thanks so much :) Commented Aug 3, 2017 at 13:30

2 Answers 2

3

A more reliable answer is to use something like this:

Sub TestBox()

Dim sVal as String
sVal = ThisWorkbook.Worksheets("Sheet1").Cells(1,1).Value
'sVal = ActiveSheet.Cells(1,1).Value 
'above can be used as well, but its not 100% reliable.

Msgbox sVal

End Sub

Notice how i explicitly declared my objects and I avoided Activate.

Sign up to request clarification or add additional context in comments.

4 Comments

What is so bad with "ActiveSheet.Activate" anyhow?
1) ActiveSheet.Activate is redundant, since ActiveSheet already refers to the activated sheet. 2) At any given point in the code the ActiveSheet may not be what you expect it to be. In this simple code you have in your question it won't throw an error or mess up your code, but it's good practice to avoid it unless absolutely needed (it's rare that it is, but at times it is). @Kagerjay
@Kagerjay ^^ and (unless I am completely confused - which is not unusual - and hopefully Scott will correct me if I am wrong) Activate (and Select) is quite slow in processing terms.
@YowE3K -- when used over and over yes. When used once or twice when needed, not so much.
1

Cells are indexed at 1 as the initial value when referencing the entire sheet (as opposed to ActiveCell.Offset, those are indexed at 0)

A1= Cells(1,1)

so its

Sub TestBox()
ActiveSheet.Activate
MsgBox (Cells(1, 1).Value)
End Sub

to output the current sheet's A1 value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.