使用VBA向单元格添加单引号

时间:2012-07-13 18:35:59

标签: excel-vba vba excel

我试图通过使用Chr(39)将单引号添加到列中的值,但我只得到第二个引号。 例如我想要'value',但我得到 value'

但如果我使用Chr(34)使用双引号就可以了,我得到“value”

Sub AddQuote()
Dim myCell As Range
    For Each myCell In Selection
        If myCell.Value <> "" Then
            myCell.Value = Chr(39) & myCell.Value & Chr(39)
        End If
    Next myCell
End Sub

谢谢, 基兰

3 个答案:

答案 0 :(得分:4)

我更喜欢这种语法。不要遍历每个单元格,只需将整个选择读入数组,对数组执行操作,然后将数组内容转储回工作表。最多两次工作表触摸。

Sub AddQuote()

  Dim i As Long, j As Long
  Dim inputData As Variant
  Dim outputData As Variant

  ' only act on a range
  If TypeName(Selection) = "Range" Then
    ' assign selection value to a Variant array
    inputData = Selection.Value
    ' create an output array of the same size
    ReDim outputData(LBound(inputData) To UBound(inputData), _
                     LBound(inputData, 2) To UBound(inputData, 2))

    ' loop through all array dimensions
    For i = LBound(inputData) To UBound(inputData)
      For j = LBound(inputData, 2) To UBound(inputData, 2)
        ' array element will be = Empty if cell was empty
        If Not IsEmpty(inputData(i, j)) Then
          outputData(i, j) = Chr(39) & Chr(39) & inputData(i, j) & Chr(39)
        End If
      Next j
    Next i

    Selection.Value = outputData
  End If

End Sub

它还考虑了多列选择。

答案 1 :(得分:2)

第一个引号'表示单元格被视为文本。

因此,您必须在LHS上使用两个单引号,并在右侧使用一个单引号才能正确显示。

请注意 A1 = ''test' A2 = ''abc'

然后=A1&A2会根据您的预期给您'test''abc'

答案 2 :(得分:2)

只需添加另一个单引号:

Sub AddQuote()
Dim myCell As Range
    For Each myCell In Selection
        If myCell.Value <> "" Then
            myCell.Value = Chr(39) & Chr(39) & myCell.Value & Chr(39)
        End If
    Next myCell
End Sub