简体   繁体   中英

How to assign range in a string VBA?

I have a code to highlight words in a cell based on the values in another cells. It works perfectly when I assign FindW = Range("X1") . However the code does not seem to work when I assign range eg: ("X1:X1000") to the string value FindW and I could not find a way to fix this.

Does anyone have any idea?

See the code below:


Dim Rng As Range
Dim FindW As String
Dim xTmp As String
Dim x As Long
Dim m As Long
Dim y As Long
Dim ws As Worksheet

Set ws = ThisWorkbook.Worksheets("Übersicht")

Application.ScreenUpdating = False
Application.EnableEvents = False
    

With ws

FindW = Range("X1:X1000")
y = Len(FindW)



For Each Rng In Range("C:H")
  With Rng
    m = UBound(Split(Rng.Value, FindW))
    If m > 0 Then
      xTmp = ""
      For x = 0 To m - 1
        xTmp = xTmp & Split(Rng.Value, FindW)(x)
        .Characters(Start:=Len(xTmp) + 1, Length:=y).Font.ColorIndex = 3
        xTmp = xTmp & FindW
      Next
    End If
  End With
Next Rng
     
End With
End Sub

You can't put the values of a Range of multiple cells directly into a single String variable. However, you can create a String Array and store each cell value individually in the String Array.

The easiest solution is to just use a Variant variable, and put the range values directly in it, like this:

Dim mrange As Range
Dim mVariant As Variant
mVariant = myRange.Value

If you really need your variable to be a String , there are multiples ways to do so:

For example, you can loop through each cell of the Array using something like:

For each mCell in mRange.Cells
    mString(i) = mCell.Value
    i = i + 1
Next mCell

mRange being your Range, and mString being a String Array. This solution requires for you to know how many cells are in the Range, since the String array needs to be defined with a size.

If you don't know the size of your Range, you can add a step and use a Variant variable.
See here .

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