使用Access VBA格式化Excel texttocolumn

时间:2015-06-03 19:58:10

标签: excel access-vba

我正在尝试使用访问VBA转换excel文件中的所有列。我想使用TextToColumns函数将列从文本转换为通用格式。

我正在尝试使用的代码如下:

Dim oExcel As Excel.Application
Dim owb As Workbook
Dim oWS As Worksheet      
Dim rngS As Range

Set oExcel = New Excel.Application
Set owb = oExcel.Workbooks.Open(sPath)
Set oWS = owb.Sheets(1)
Set rngS = oWS.Columns

Do While rngS <> ""

For Each rngS In oWS
    rngS.TextToColumns rngS.Cells(1, 1), xlDelimited, xlDoubleQuote, False, True, False, False, False, False, xlGeneralFormat

Next
    Loop

我可以将TexttoColumns用于单个列,但很难让它在电子表格中的所有列中移动。我知道这看起来像是严重编码的代码所以任何帮助都会非常感激!

1 个答案:

答案 0 :(得分:0)

由于您正在使用Access,这似乎是合理的,这是一个连续的数据块,可能有空白单元格,但没有完全空白的行和/或列分隔的值 islands 。如果是这种情况,则可以利用工作表的Range.CurrentRegion property来管理要处理的单元格。

Dim oExcel As Excel.Application, oWB As Workbook, oWS As Worksheet
Dim c As Long

Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open(sPath)
Set oWS = oWB.Sheets(1)

With oWS.Cells(1, 1).CurrentRegion
    For c = 1 To .Columns.Count
        With .Columns(c)
            .TextToColumns Destination:=.Cells(1), DataType:=xlFixedWidth, FieldInfo:=Array(0, xlGeneralFormat)
        End With
    Next c
End With

我更喜欢 xlFixedWidth 方法,而只提供单个 FieldInfo 参数集。