以斜体打印字符串

时间:2014-06-19 17:08:47

标签: vba excel-vba word-vba excel

我将输入作为来自Userform的字符串,我需要在单元格中输出它们。在输出中,所有字符串都连接在一起,但只有少数字符串用斜体字表示。我无法输出斜体字符串。我已经尝试搜索文档,堆栈交换和其他一些博客,但所有这些都需要从单元格中进行选择,而不是操纵从Userform获得的字符串。非常感谢任何帮助或指示。

现在输出:[1] R. Welder。如何焊接。焊接车间:出版社,2014年,第25-32页。

期望输出:[1] R. Welder。 如何焊接。焊接车间:出版社,2014年,第25-32页。

Private Sub Ok_Click()
Dim emptyRow As Long
Dim bookAuthor, bookTitle, loc, publish, yearBook, pageBook As String

'Make Sheet2 active
 Sheet2.Activate

'Determine emptyRow
emptyRow = WorksheetFunction.CountA(Range("A:A")) + 1

'Format Information
bookAuthor = Author.Value + ". "
bookTitle = TitleOfBook.Value + ". " 'Needs to be Italicized
'bookTitle.Font.Italic 'Error: Object Required
'TitleOfBook.Font.Italic = True 'Italicizes in userform but not in cell
loc = Location.Value + ": "
publish = Publisher.Value + ", "
yearBook = Year.Value + ", "
pageBook = "pp. " + Pages.Value + ". "

'Transfer information
Cells(emptyRow, 1).Value = "[" + CStr(emptyRow) + "] " + bookAuthor + bookTitle + loc + publish + yearBook + pageBook

Unload Me
End Sub'

1 个答案:

答案 0 :(得分:3)

将您写入的单元格的字体样式设置为斜体的单元格,而不是字符串;

With Range("A1")
    .Font.Italic = True
    .Value = "Roast Beef"
End With

修改;要使单元格的部分斜体按偏移和长度选择其内容:

emptyRow = 1
bookAuthor = "R. Welder."
bookTitle = "How to weld"
loc = "Welding Shop"
publish = "Publisher"
yearBook = "2014"
pageBook = "pp25-32"

Dim temp As String, begin As Long
'// store everything upto the start of italic part
temp = "[" & emptyRow & "] " & bookAuthor & " "
'// store its length
begin = Len(temp)

With Range("A1")
    '// set the value to everything
    .Value = temp & bookTitle & " " & loc & " " & publish & " " & yearBook & " " & pageBook
    '// we know where the italic text need to be
    .Characters(begin + 1, Len(bookTitle)).Font.Italic = True
End With