从多单元格范围获取格式化值

时间:2011-04-08 05:49:55

标签: excel vba excel-vba

Dim myText As String
myText= Range("a3").Text

返回单元格A3中的格式化值,但

myText= Range("a3:c7").Text

给了我一个错误。

如何从多单元格区域获取表示格式化值的字符串,同时保留数字格式?即,输出文本的格式与从范围复制粘贴到文本编辑器的格式相同。

5 个答案:

答案 0 :(得分:9)

使用一个单一语句(无循环)将多个单元格值放入数组的唯一方法是使用Variant数组。

Dim varItemName As Variant
varItemName = Range("a3:c7")

如果您确实需要输入String类型的名称,那么稍后使用它们时只需CStr

output = FunctionRequiringStringArgument(CStr(varItemName(1,2))

编辑:好的,你想要的格式与图纸格式相同。

这是一个完整的工作示例。

Dim strMyFormat1 As String
Dim varItemName As Variant
Dim strItemName() As String
Dim strItemNameBF() As String
Dim iCol As Long
Dim iRow As Long
Dim rngMyRange As Range

Set rngMyRange = Range("A3:C7")
varItemName = rngMyRange
ReDim strItemName(LBound(varItemName, 1) To UBound(varItemName, 1), _
    LBound(varItemName, 2) To UBound(varItemName, 2))

'// Take a sample of the format
strMyFormat1 = Range("A3").NumberFormat

'// Apply format sample to all values
For iRow = LBound(varItemName, 1) To UBound(varItemName, 1)
    For iCol = LBound(varItemName, 2) To UBound(varItemName, 2)
        strItemName(iRow, iCol) = Format(varItemName(iRow, iCol), strMyFormat1)
    Next iCol
Next iRow
'// Can also apply to only some values -- adjust loops.
'// More loops go here if many format samples.

'// If all cells have different formats, must use brute force -- slower.
ReDim strItemNameBF(1 To rngMyRange.Rows.Count, _
    1 To rngMyRange.Columns.Count)
For iRow = 1 To rngMyRange.Rows.Count
    For iCol = 1 To rngMyRange.Columns.Count
        strItemNameBF(iRow, iCol) = rngMyRange.Cells(iRow, iCol).Text
    Next iCol
Next iRow

答案 1 :(得分:6)

For Each c In Range("a3:c7")
    ItemName = c.Text
Next c

这将为您提供一个接一个的单元格。

答案 2 :(得分:5)

这是其中一个帖子的修改版本,它对我有用。

    Function Range2Text(ByVal my_range As Range) As String
        Dim i As Integer, j As Integer
        Dim v1 As Variant
        Dim Txt As String

        v1 = my_range
        For i = 1 To UBound(v1)
            For j = 1 To UBound(v1, 2)
                Txt = Txt & v1(i, j)
            Next j
            Txt = Txt & vbCrLf
        Next i

        Range2Text = Txt
    End Function

答案 3 :(得分:1)

制作一个集合并遍历该范围的所有区域并收集文本 集合。

答案 4 :(得分:1)

dim i as integer, j as integer
Dim v1 as variant

v1=range("a3:c7")

for i=1 to ubound(v1)
  for j=1 to ubound(v1,2)
    debug.print v1(i,j)
  next j
next i
相关问题