使用数组覆盖字符串值的范围

时间:2019-09-03 09:20:08

标签: excel vba

我想将单元格的范围从整数转换为String。但是,由于我有很多数据,因此我不能对范围使用标准循环,因为它花费的时间太长。 相反,我认为使用数组并将所需的range(array)转换为字符串值。

这是我试图通过修改将范围转换为字符串的标准代码来完成的工作,而只是在数组下面使用的范围:

Sub CovertToString()

Dim ws As Worksheet
Set ws = Sheets("Sheet1")
Dim sArray As Variant
Dim LastRow As Integer
Dim cell As Variant

With ws
    LastRow = .Cells(.rows.Count, 1).End(xlUp).row
    sArray = .Range(.Cells(1, 8), .Cells(LastRow, 8))

   For Each cell In sArray
        cell = "'" & cell.Value
    Next

End With
End Sub

不幸的是,由于我不确定该如何解决,因此无法理解。

1 个答案:

答案 0 :(得分:0)

这种方式会将单元格格式转换为Text

Sub ConvertToString()

    Dim ws As Worksheet
    Dim LastCell As Range
    Dim rCell As Range

    Set ws = ThisWorkbook.Worksheets("Sheet1")
    With ws
        Set LastCell = .Cells(.Rows.Count, 1).End(xlUp).Offset(, 7)
        'Convert format to 'Text'
        .Range(.Cells(1, 8), LastCell).NumberFormat = "@"
    End With

End Sub

这种方法会将范围复制到数组,并在每个值之前添加一个',然后再发布回工作表:

Sub ConvertToString()

    Dim ws As Worksheet
    Dim LastCell As Range
    Dim vValues() As Variant
    Dim R As Long

    Set ws = ThisWorkbook.Worksheets("Sheet1")
    With ws
        'Your code is looking for last cell in column A, so offset to column H once found.
        'This is a reference to the last cell, not the row number so can be used in the range.
        Set LastCell = .Cells(.Rows.Count, 1).End(xlUp).Offset(, 7)
        vValues = .Range(.Cells(1, 8), LastCell).Value

        'Add a ' to each value.
        For R = 1 To UBound(vValues, 1)
            vValues(R, 1) = "'" & vValues(R, 1)
        Next R

        'Paste back to sheet.
        .Range(.Cells(1, 8), LastCell) = vValues
    End With

End Sub

Further reading on arrays & worksheets