我试图编写一个宏来在一个单元格中用粗体文本连接单元格。
Sub question_concat()
Dim s1 As String
Dim first As Boolean
Dim r As Long
r = 1
For Each c In Selection
If c.Font.Bold = True Then
If first = True Then
r = c.Row
first = False
End If
s1 = s1 & c.Value
Else
Cells(r, 3).Value2 = s1
first = True
s1 = ""
End If
Next
End Sub
首先,它将第3列的值设置为等于s1,但在清除s1以进行下一循环s1 = ""
后,单元格的值也会清除。
答案 0 :(得分:0)
这是因为您没有测试该行是否与您最初存储的行不同。
所以,如果你遇到2个非粗体细胞,它会:
s1
s1
!这应该会更好,即使我个人宁愿选择常规For
循环来更好地控制我经历范围的方式! ;)
Sub question_concat()
Dim s1 As String
Dim first As Boolean
Dim r As Long
r = 1
first = True
For Each c In Selection
If c.Font.Bold = True Then
If first = True Then
r = c.Row
first = False
End If
s1 = s1 & c.Value
Else
If r <> c.Row Then
Cells(r, 3).Value2 = s1
first = True
s1 = ""
End If
End If
Next c
End Sub
使用常规For
循环,就像我建议的那样:
Sub question_concat()
Dim s1 As String
Dim i As Long
Dim j As Long
Dim Rg As Range
Set Rg = Selection
For i = 1 To Rg.Rows.Count
For j = 1 To Rg.Columns.Count
Set c = Rg.Cells(i, j)
If c.Font.Bold = True Then
s1 = s1 & c.Value
Else
End If
Next j
Cells(i, 3).Value2 = s1
s1 = vbNullString
Next i
End Sub