如何修改文本导入向导VBA代码以更改特定列的列数据格式?

时间:2012-06-27 17:07:57

标签: excel vba excel-vba excel-2007

我目前正在导入包含大量数据的网址。因此,我必须每次手动浏览文本导入向导以格式化特定行。为了加快这个过程,我记录了我用来导入URL的步骤的宏。不幸的是,虽然不同URL的列标题保持不变,但它们在数据库中的位置并不一致。导入时的目标是将所有格式保留为“general”,但标题为“IdNumber”的列除外,我需要将其导入为“text”。在下面的代码中(例如),它是Array(22,2)。当我尝试导入23或24列时的其他URL时,会出现此问题。不是将IdNumber转换为“文本”,而是变成一个不同的数组。

问题:使用文本导入向导时,有没有办法用VB代码指定某些列来仅修改特定的标题列?

*注: 如果我理解正确,Array(X,X)函数的第一个数字是特定列,第二个数字是格式(1表示一般,2表示文本,...)

我的文本导入向导代码:

'open the URL (urlName is a variable set as a String and is declared earlier in the code) and go through the Text Import Wizard

Workbooks.OpenText Filename:= _
    urlName _
    , Origin:=437, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
    xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False _
    , Comma:=True, Space:=False, Other:=False, FieldInfo:=Array(Array(1, 1), _
    Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), Array(7, 1), Array(8, 1), _
    Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1), Array(14, 1), Array(15 _
    , 1), Array(16, 1), Array(17, 1), Array(18, 1), Array(19, 1), Array(20, 1), Array(21, 1), _
    Array(22, 2), Array(23, 1), Array(24, 1), Array(25, 1), Array(26, 1), Array(27, 1), Array( _
    28, 1), Array(29, 1), Array(30, 1), Array(31, 1), Array(32, 1)), TrailingMinusNumbers _
    :=True

1 个答案:

答案 0 :(得分:1)

Sub tester()

    Dim arr, a
    arr = GetFieldInfoArray(32, 22) 'position from first load=22...
    For Each a In arr
        Debug.Print Join(a, ",")
    Next a

    Workbooks.OpenText Filename:=urlName, Origin:=437, StartRow:=1, _
              DataType:=xlDelimited, TextQualifier:=xlDoubleQuote, _
              ConsecutiveDelimiter:=False, Tab:=False, Semicolon:=False, _
              Comma:=True, Space:=False, Other:=False, _
              FieldInfo:=arr, TrailingMinusNumbers:=True


End Sub

'EDIT: adjust array lower bound from 1 to 0...
Function GetFieldInfoArray(NumFields As Integer, IdPosition As Integer)
    Dim arr(), x

    ReDim arr(0 To NumFields-1)
    For x = 1 To NumFields
        arr(x-1) = Array(x, IIf(x = IdPosition, 2, 1))
    Next x

    GetFieldInfoArray = arr
End Function