如何删除单元格开头和结尾的空格?

时间:2019-08-21 09:21:05

标签: excel vba csv

我在电子表格中导入了CSV。当我运行刷新宏时,它将在每个单元格的开头和结尾添加一个空格。

我正试图通过在单元格的开头和结尾(不在两者之间)使用相同的宏修剪所有空格来对此进行补救。

在单个单元上执行此操作不会出现问题

Range("F10").Value = Trim(Range("F10").Value)

在一定范围内,它什么也不做,没有错误消息,只是没有反应

Dim cell As Range, areaToTrim As Range
Set areaToTrim = Sheet1.Range("A6:J10")
For Each cell In areaToTrim
    cell.Value = Trim(cell.Value)
Next cell

实际上,我不希望它是A6到J10,我只是把它放进去看看它是否适用于某个范围。我希望它是A6到J的最后一行。所以我希望我的最终代码是

Dim lastrowindex As Long
lastrowindex = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row

Dim db_range_start As String
Dim db_range_end As String

db_range_start = "A6"
db_range_end = "J" & lastrowindex
db_range_region = db_range_start & ":" & db_range_end

Dim db_range As Range
Set db_range = Range(db_range_region)

Dim cell As Range, areaToTrim As Range
Set areaToTrim = Sheet1.Range(db_range)
For Each cell In areaToTrim
    cell.Value = Trim(cell.Value)
Next cell

但这会引发

  

对象Range的方法值失败。

1 个答案:

答案 0 :(得分:1)

接下来,您将代码db_range声明为Range,然后尝试使用它来使用Sheet1.Range(db_range)来指定范围,这将采用字符串而不是字符串来简化并简化代码。范围:

Sub Trim_Range()
Dim ws As Worksheet: Set ws = Sheet1
Dim LastRow As Long
Dim c As Range
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

For Each c In ws.Range("A6:J" & LastRow)
    c.Value = Trim(c.Value)
Next c
End Sub