列选择选择意外的工作表列

时间:2019-06-28 16:57:05

标签: excel vba

我录制了一个宏,其中包括选择列和设置宽度。直到我对前面的代码进行了一些更改(通过在命名范围而不是宏记录的文字范围中进行编辑)后,此方法才起作用。

现在,选择列的行似乎未按预期运行。 “ Columns(” A:A“)。Select”选择列A:P!

在我看来,我引入了一个错误,但我没有看到它。

Sub DataImport()

    Range("A10").Select

    With ThisWorkbook.ActiveSheet.Range("Z1")
        .Formula = "=VLookup(C5, FileNameDictionary, 3, False)"
        .Value = .Value
        End With

    file_name = Range("Z1").Value
    Range("z1").Value = ""

    cx_name = "TEXT;" & Range("Cover!$C$18").Value & file_name

    With ActiveSheet.QueryTables.Add(Connection:=cx_name, Destination:=Range("ResultGrid"))
        .Name = ""
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With

    Columns("B:R").Select
    Selection.ColumnWidth = 6
    Columns("A:A").Select
    Selection.ColumnWidth = 10
    Range("A10").Select

    HideEmptyRows

End Sub

1 个答案:

答案 0 :(得分:0)

这似乎已经解决了问题:

Dim ws As Worksheet
Set ws = ActiveSheet
With ws.Columns("B:R")
    .ColumnWidth = 6
    End With

With ws.Columns("A:A")
    .ColumnWidth = 10
    End With