首页 > 解决方案 > 修剪一些单元格包含空格,一些包含公式的数据

问题描述

我在 Excel 文件中有大量数据。我有超过 3000 行跨越 A 到 CZ 列。

在开始使用数据之前,我需要修剪所有数据。

当我使用 VBA 时,它需要很长时间,并且出现错误“类型不匹配”。

一些单元格包含空格,一些包含公式,一些包含与另一个 Excel 文件的公式链接。

Worksheets("Sheet1").Activate
For Each cell In ActiveSheet.UsedRange.SpecialCells(xlCellTypeConstants)
    If cell.HasFormula = False Then
        cell.Value = Trim(cell)
    End If
Next cell

它想修剪没有公式但出现错误的单元格。

标签: excelvba

解决方案


文本到列、固定宽度、完成将快速删除前导/尾随空格。

dim i as long

with Worksheets("Sheet1")
    for i=.cells(1, .columns.count).end(xltoleft).column to 1 step -1
        with .columns(i)
            .cells.TextToColumns Destination:=.cells(1), DataType:=xlFixedWidth, _
                                 FieldInfo:=Array(0, 1)
        end with
    next i
end with

顺便说一句,如果你想将多个中间空格(例如data datato data data)减少到一个空格,你需要使用Application.Trim(...)not VBA.Trim(...)


推荐阅读