VBA to display predefined value automatically

David_8055

New Member
Joined
Jul 6, 2022
Messages
7
Office Version
  1. 365
Platform
  1. Windows
  2. MacOS
  3. Mobile
Is there a way to write a vba code to automatically display certain text in column C (for eg: “2021a”) if column B contains any value (regardless of text or number). I can write this is excel formula by using isText and IsNumber commands with IF and OR clause. Can some VBA experts give me a solution please? So basically what I want to display at C1 is “Data” C2, C3, C4,….. is “2021a” Regardless of the value at B.

Also how can this command run automatically every time I open this spreadsheet?
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
Hi David,

is this what you want

VBA Code:
Private Sub Workbook_Open()

Dim rng As Range, cell As Range
Set rng = Range("C2:C10")

For Each cell In rng

If cell.Offset(, -1) <> "" Then
cell.Value = "2021a"

    Else
    cell.ClearContents

End If
    Next cell

End Sub
 
Upvote 0
Solution
Hi Hrayani,
Thanks much. It works.
Just 1 question. How will I run it automatically every time I open my spreadsheet?
 
Upvote 0
Use worksheet_activate event
Using specialcells may help code run faster, in case you data expands to thousand of rows.
VBA Code:
Option Explicit
Private Sub Worksheet_Activate()
Application.ScreenUpdating = False
Range("B1:B100000").Copy ' adjust to actual possible range
Range("C1").PasteSpecial xlPasteValues
Application.CutCopyMode = False
Selection.SpecialCells(xlCellTypeConstants).Value = "2021a"
Range("A1").Select
Application.ScreenUpdating = True
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,925
Messages
6,122,301
Members
449,078
Latest member
nonnakkong

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top