我更喜欢这种语法。无需遍历每个单元格,只需将整个选择读入一个数组,对数组进行操作,然后将数组内容转储回工作表。最多两次触摸工作表。
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
它还考虑了多列选择。