Passing values from Excel to Word with VBA

时间:2017-08-04 12:38:48

标签: excel vba excel-vba

For Each cell In rng
    workSheetName = Format(SaturdayIsComing(), "mm-dd-yyyy") & " " & cell.Value
    If WorksheetExists(workSheetName) Then
        Dim localRange, localCell As Range
        Set localRange = Worksheets(workSheetName).Range("D8:D19")
        Dim contents As Variant
        contents = ""
        Dim firstLine As Boolean
        firstLine = True
        For Each localCell In localRange
            If Len(localCell.Value) > 0 Then
                If firstLine Then
                    contents = contents & localCell.Value & Chr(11)
                Else
                    contents = contents & Chr(9) & Chr(9) & Chr(9) & localCell.Value & Chr(11)
                End If
            Else
                contents = fixString(contents)
            End If
            If Len(contents) > 0 Then
                firstLine = False
            End If
        Next localCell

        For Each cc In wDoc.SelectContentControlsByTag(cell.Value & "Notes")
            If Len(contents) > 0 Then
                cc.Range.Text = fixString(contents)
            Else
                cc.Range.Text = "No Issues Found"
            End If
        Next
    Else
        errorCodesString = errorCodesString & cell.Value & ":"
    End If
Next cell

Output to Word

 Forgot to terminate the meeting
 This is a test message\'s

If my cell contains a ' then I get an error saying

One of the values passwed to this method or property is incorrect

I know a ' is a comment in VBA. How do I go around this while preserving the notes that someone had added to the Excel cell?

2 个答案:

答案 0 :(得分:1)

You need to write a piece of code to search for quotes, either the single (') or double (") variety and either add a backslash before them OR double the character so '' in place of ' and "" in place of " and run this on contents before assigning it to cc.Range.Text.

This routine can also check for other instances of incorrect strings and fix them.

Something like this would do:

Function fixString(ByVal strIn As Variant) As String
Dim i As Integer

Const strIllegals = "\'"""
For i = 1 To Len(strIllegals)
strIn = Replace(strIn, Mid$(strIllegals, i, 1), "\" & Mid$(strIllegals, i, 1))
Next i
fixString = strIn
End Function

Conversion Picture

答案 1 :(得分:0)

Try changing cell.Value to Replace(cell.Value, "'", "")

Or is it contents that has the apostrophe in it? A bit confusing.

Try changing contents to Replace(contents , "'", "")