2017-01-24 79 views
0

我正试图编写一个宏来将单元格与粗体文本连接在一个单元格中。在Excel中使用VBA宏,重置变量将重置单元格值

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 

起初它设置第三列等于s1的值,但清除S1为下一个循环s1 = ""后,细胞的值也被清除。

回答

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 
+0

我真的不知道什么是你想实现的,但我觉得首先是'灰暗布尔:第一=真'会帮助你。 – Vityata

+1

@Vityata:的确,它需要初始化! Thx指出它! – R3uK

+0

问题是,当我将s1指定给单元格时,它显示单元格上的文本。但在重置s1(s1 =“”)后,该单元格的值将消失。 – Farhad

相关问题