Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
628 views
in Technique[技术] by (71.8m points)

excel - VBA copy cells value and format

How can I amend the following code in order to copy not only the value but also the fonts style, e.g. bold or not bold. Thanks

Private Sub CommandButton1_Click()
Dim i As Integer
Dim a As Integer
a = 15
For i = 11 To 32
  If Worksheets(1).Cells(i, 3) <> "" Then
    Worksheets(2).Cells(a, 15) = Worksheets(1).Cells(i, 3).Value
    Worksheets(2).Cells(a, 17) = Worksheets(1).Cells(i, 5).Value
    Worksheets(2).Cells(a, 18) = Worksheets(1).Cells(i, 6).Value
    Worksheets(2).Cells(a, 19) = Worksheets(1).Cells(i, 7).Value
    Worksheets(2).Cells(a, 20) = Worksheets(1).Cells(i, 8).Value
    Worksheets(2).Cells(a, 21) = Worksheets(1).Cells(i, 9).Value
    a = a + 1
  End If
Next i
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Instead of setting the value directly you can try using copy/paste, so instead of:

Worksheets(2).Cells(a, 15) = Worksheets(1).Cells(i, 3).Value

Try this:

Worksheets(1).Cells(i, 3).Copy
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteFormats
Worksheets(2).Cells(a, 15).PasteSpecial Paste:=xlPasteValues

To just set the font to bold you can keep your existing assignment and add this:

If Worksheets(1).Cells(i, 3).Font.Bold = True Then
  Worksheets(2).Cells(a, 15).Font.Bold = True
End If

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...