简体   繁体   中英

How to replace an InputBox with a predifned range of cells in Excel VBA

I have vba code snippet which I am trying to modify so that I can automatically color the text in each cell in a predefined range of cells. The code snippet I provides an "InputBox" for the user to enter the range, however, I want to replace this prompt in the code with a predefined range so the user is never prompted. Can you kindly point me in the right direction. This is the code I have been working with. Many thanks in advance.

Sub changeTextColor()
Dim rng As Range
Dim WorkRng As Range
Dim xRed As Byte
Dim xGreen As Byte
Dim xBlue As Byte
On Error Resume Next

xTitleId = "Prompt Box"  'I commented this out prior to running
Set WorkRng = Application.Selection

.I Inserted this line of code and this is the line where I keep on getting errors
'Set WorkRng = ActiveSheet.Range("C4:I55").Select

'I commented this out prior to running
Set WorkRng = Application.InputBox("Range", "", WorkRng.Address, Type:=8)
For Each rng In WorkRng
xRed = Application.WorksheetFunction.RandBetween(0, 255)
xGreen = Application.WorksheetFunction.RandBetween(0, 255)
xBlue = Application.WorksheetFunction.RandBetween(0, 255)
rng.Pattern = xlSolid
rng.PatterColorIndex = xlAutomatic
rng.Font.Color = VBA.RGB(xRed, xGreen, xBlue)
Next
End Sub

Where you have Set WorkRng = ActiveSheet.Range("C4:I55").Select you should have just Set WorkRng = ActiveSheet.Range("C4:I55") . In the first code, you select the ranges (but don't do anything with the selection*). In my amended code, I assign WorkRng to the range that you want - equivalent to what you do with your InputBox .

You also do not need Set WorkRng = Application.Selection . For starters, you are relying on the user having selected something before running the macro.

(*) As a handy hint, should never .Select ranges etc. that you want to manipulate in VBA code because the user could quite easily change your selection on you. If you already know the range you want, just work with that object directly.

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