如何在每个循环中将different.txt文件导入到不同的工作簿?

时间:2019-01-29 20:40:44

标签: excel vba import sap sap-gui

我对VBA极为陌生,可能缺少一些简单的东西,但我迷路了。

我通过在Excel工作表中输入5个不同的数字(平面MSN)从SAP提取数据,然后运行宏。 How its set up

宏选择第一个MSN单元格,使用该单元格引用提取正确的数据,另存为文本文件,然后创建一个新的工作簿以保存该数据并最终导入文本文件。

我想创建一个循环,以便它创建5个不同的工作簿,每个MSN值一个。我遇到的问题是正确引用.txt文件的位置和名称,因为它会更改每个循环。

该txt保存为:USA_Clusters_MSN_STN

“ USA_Clusters_”&ActiveCell.Value&“ _”&ActiveCell.Offset(0,-1).Value&“ .txt”

If Workbooks("ClusterSheet.xlsm").Sheets("Start").Range("B2").Value = ActiveCell.Value Then

Set Newbook = Workbooks.Add
With Newbook
    .Title = "MSN"
    .Subject = "MSN"
End With

Workbooks("ClusterSheet.xlsm").Activate
Sheets("Start").Select
Range("B2").Select

With Newbook
.SaveAs Filename:="USA_Clusters_" & ActiveCell.Value & "_" & ActiveCell.Offset(0, -1).Value & ".xls"
End With
 ElseIf Workbooks("ClusterSheet.xlsm").Sheets("Start").Range("B3").Value = ActiveCell.Value Then

Set Newbook2 = Workbooks.Add
With Newbook2
    .Title = "MSN"
    .Subject = "MSN"
End With

Workbooks("ClusterSheet.xlsm").Activate
Sheets("Start").Select
Range("B3").Select

With Newbook2
.SaveAs Filename:="USA_Clusters_" & ActiveCell.Value & "_" & ActiveCell.Offset(0, -1).Value & ".xls"
End With

这是我通过从头开始引用所选单元格来创建新工作簿的方式

With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;C:\Users\chplau04\Documents\Clusters\Clusters Week of Jan-21\USA_Clusters_8857_42.txt" _
    , Destination:=Range("$A$1"))
    .Name = "USA_Clusters_8857_42"
    .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 = 8
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileOtherDelimiter = "|"
    .TextFileColumnDataTypes = Array(1)
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False

当我导入时,我需要找到.txt文件的位置和名称。

如何创建将正确文件导入正确工作表的导入宏?

0 个答案:

没有答案