![](/img/trans.png)
[英]Conditionally format a cell, or populate a cell based on the contents of another cell, if the 2nd if greater than 3.
[英]Apply format to part of a cell based on contents of another cell
我正在嘗試根據另一個單元格的內容將特定格式應用於單元格的一部分。
我是VBA的初學者,並且能夠根據字符串中的位置將不同的格式應用於單元格的某些部分,但是不能超出此范圍。
表格1的F列包含SKU字符串(以逗號分隔)。 在對該產品執行檢查后,我想將SKU設為粗體。 我將數據導入表2,其中D列包含已檢查產品的SKU。
綜上所述,我希望基於工作表2的D列中SKU的存在,將工作表1的F列中的字符串中的單個SKU加粗。
有人可以協助提供必要的VBA代碼嗎? 我將非常感謝您的協助。
(我搜索了很多論壇,但到目前為止尚未找到答案)
編輯:我發現以下內容,並且可以使用它。 它基於設置變量,但不是動態的:
Sub test()
For row_num = 1 To 13
'Cell contents
cell_text = Cells(row_num, 1)
'Same contents split into three parts and saved in an array
text_array = Split(cell_text, " ")
'Length of part 1
length_1 = Len(text_array(0))
'Length of part 2
length_2 = Len(text_array(1))
'Set ITALICS for Part 1
Cells(row_num, 1).Characters(1, length_1).Font.Color = vbGreen
'Set BOLD for Part 2
Cells(row_num, 1).Characters(length_1 + 2, length_2).Font.Bold =
True
Next
End Sub
這仍然是一個假設的問題,但是以下文件中有兩列內容的一個很小的示例
好的,因此,如果要正確理解並基於您的文本“因此,我希望基於表格2的D列中存在該SKU,我希望表格1的F列中的字符串中的單個SKU為粗體” :
我會盡力引導您正確的方向:
1)。 首先,您要動態遍歷Sheets(2)的D列中的所有行。 有很多方法可以做到這一點,但是我個人喜歡使用.UsedRange
。 例如:
Dim CL As Range
For Each CL In Sheets(2).UsedRange.Columns(4).Rows
'Your code Part 2
Next CL
2)。 現在,您必須在Sheets(1)的F列中找到這些值的匹配項。 一種明智/快速的方法是利用.FindNext
查看有價值的部分。 實際上,它看起來像這樣:
Dim CLL as Range
Dim FirstAddress as String
With Sheets(1).Columns(6)
Set CLL = .Find(What:=CL.Value, LookIn:=xlValues, Lookat:=xlPart)
If Not CLL Is Nothing Then
FirstAddress = CLL.Address
Do
'You code Part 3
Set CLL = .FindNext(CLL)
Loop While Not CLL Is Nothing And CLL.Address <> FirstAddress
End If
End With
3)。 現在,我們正在尋找包含所需值的適當單元格,我們需要確定值在整個字符串中的位置。 我們可以使用方便的名稱為.InStr
。 該函數的作用是確定值的第一個字符在整個字符串中的位置。 實際上,它看起來像這樣:
Dim POS as Long
POS = InStr(1, CLL.Value, CL.Value)
“ 1”表示我們要從字符串中的哪個位置開始搜索。 CLL.Value是我們要查找的整個字符串,使CL.Value成為我們的搜索值。
4)。 現在我們可以指示字符串的起始位置,並且我們想知道我們的搜索值的長度,可以使用.Len
函數生成數字值。
=Len(CL.Value)
5)。 快到了嗎? 只需使用.Characters
使字符加粗。 我們可以將Bold
設置為True
。 它相當不錯,用法如下:
CLL.Characters(POS, Len(CL.Value)).Font.Bold = True
此處的POS
用作我們的起始位置,而LEn(CL.Value)
顯然是我們所需的粗體長度。
6)。 我們來了。 如果我們將所有這些放在一起:
Sub CreateBold()
Dim CL As Range, CLL As Range
Dim FirstAddress As String
Dim POS As Long
For Each CL In Sheets(2).UsedRange.Columns(4).Rows
With Sheets(1).Columns(6)
Set CLL = .Find(What:=CL.Value, LookIn:=xlValues, Lookat:=xlPart)
If Not CLL Is Nothing Then
FirstAddress = CLL.Address
Do
POS = InStr(1, CLL.Value, CL.Value)
CLL.Characters(POS, Len(CL.Value)).Font.Bold = True
Set CLL = .FindNext(CLL)
Loop While Not CLL Is Nothing And CLL.Address <> FirstAddress
End If
End With
Next CL
End Sub
希望這能回答您的問題,並且已經足夠清楚地理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.