简体   繁体   English

如何使用 VBA 转置通过 QueryTables 导入的值?

[英]How can I transpose values imported via QueryTables using VBA?

I have created a VBA code where it prompts for a CSV file and imports it.我创建了一个 VBA 代码,它提示输入 CSV 文件并导入它。 However, it imports values as a row.但是,它将值作为一行导入。 I need them to be imported as a column.我需要将它们作为列导入。 How?如何?

I tried setting the Range to $B$2:$B$10 , but that did not help.我尝试将 Range 设置为$B$2:$B$10 ,但这没有帮助。 I tried searching QueryTables for "transpose data on import" directive, but so far have not found one.我尝试在 QueryTables 中搜索“在导入时转置数据”指令,但到目前为止还没有找到。

Code:代码:

Sub Button_Import_Click()
    
    Dim Ret
    
    Ret = Application.GetOpenFilename("Nameplate File (*.txt), *.txt")
    
    If Ret <> FALSE Then
        With ActiveSheet.QueryTables.Add(Connection:= _
             "TEXT;" & Ret, Destination:=Range("$B$2"))
            .TextFileParseType = xlDelimited
            .RefreshStyle = xlOverwriteCells
            .TextFileCommaDelimiter = TRUE
            .Refresh
            
        End With
    End If
    
End Sub

Data Sample数据样本

Filename: text.txt文件名: text.txt

Data: product,30,370 psi,80 lbs,description,80,March,20,2021数据: product,30,370 psi,80 lbs,description,80,March,20,2021

Expectation for Excel:对 Excel 的期望:

B2: product
B3: 30
B4: 370 psi
...
B10: 2021

I ended up posting QueryTables result to an empty cell range A20 in this case and then using Transpose to copy over cells to the required location B2:B10在这种情况下,我最终将 QueryTables 结果发布到空单元格范围A20 ,然后使用 Transpose 将单元格复制到所需的位置B2:B10

If Ret <> False Then
    With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;" & Ret, Destination:=Range("$A$20"))
    .TextFileParseType = xlDelimited
    .RefreshStyle = xlOverwriteCells
    .AdjustColumnWidth = False
    .TextFileCommaDelimiter = True
    .Refresh

    End With
    
    'Transpose
    Dim DirArray As Variant
    DirArray = Range("A20:I20").Value
    Range("B2:B10").Value = Application.WorksheetFunction.Transpose(DirArray)
    Range("A20:I20").Clear
    
End If

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM