|
前回の続きでわからないことがあって困ってます
前回の処理にシートを追加してCSVファイルを連結したのを入れる処理を加えたいのですがうまくいかずエラーが起きます
わかる方いれば教えてください
Sub CSV結合してBookへ出力()
Dim fs As Object, fd As FileDialog
Dim fStr As String, fName As Variant, i As Integer
Dim iz As Long
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = True
.Title = "データ選択(ファイル参照)"
.Filters.Add "テキストファイル", "*.csv"
If .Show = 0 Then Exit Sub
If .SelectedItems.Count < 2 Then
MsgBox "データを複数選んでください"
Exit Sub
End If
End With
Set fs = CreateObject("Scripting.FileSystemObject")
iz = fd.SelectedItems.Count
For i = 1 To iz
With fs.OpenTextFile(fd.SelectedItems(i), 1)
fStr = fStr & .ReadAll
.Close
End With
Next i
fName = Replace(LCase(fd.SelectedItems(iz)), ".csv", "$.csv")
With fs.CreateTextFile(fName)
.Write fStr
.Close
End With
Dim WS As Worksheet
Set WS = Workbooks.Add(6).Worksheets(1)
テキストファイルのインポート fName, WS
fName = Application.GetSaveAsFilename( _
InitialFileName:="ファイル.xls", _
FileFilter:=",*.xls")
If fName = False Then Exit Sub
Application.EnableEvents = False
ActiveWorkbook.SaveAs fName, FileFormat:=xlNormal
Application.EnableEvents = True
End Sub
Sub シートを追加してそこにインポート()'ここから追加した処理でうまくいきま せん
Dim fs2 As Object, fd2 As FileDialog
Dim fStr2 As String, fName2 As Variant, i2 As Integer
Dim iz2 As Long
Set fd2 = Application.FileDialog(msoFileDialogFilePicker)
With fd2
.AllowMultiSelect = True
.Title = "データ選択(ファイル参照)"
.Filters.Add "テキストファイル", "*.csv"
If .Show = 0 Then Exit Sub
If .SelectedItems.Count < 2 Then
MsgBox "データを複数選んでください"
Exit Sub
End If
End With
Set fs2 = CreateObject("Scripting.FileSystemObject")
iz2 = fd2.SelectedItems.Count
For i2 = 1 To iz2
With fs.OpenTextFile(fd.SelectedItems(i2), 1)
fStr2 = fStr2 & .ReadAll
.Close
End With
Next i2
fName2 = Replace(LCase(fd2.SelectedItems(iz2)), ".csv", "$.csv")
With fs2.CreateTextFile(fName)
.Write fStr2
.Close
End With
Dim WS As Worksheet
Set WS = Worksheets.Add(After:=Worksheets(1))
fName = Application.GetSaveAsFilename( _
InitialFileName:="ファイル.xls", _
FileFilter:=",*.xls")
If fName2 = False Then Exit Sub
Application.EnableEvents = False
ActiveWorkbook.SaveAs fName, FileFormat:=xlNormal
Application.EnableEvents = True
End Sub
Sub テキストファイルのインポート(CSVname, ByVal WS As Worksheet)
With WS
With .QueryTables.Add(Connection:= _
"TEXT;" & CSVname, Destination:=WS.Range("A1"))
.Name = "foo"
.FieldNames = True
.AdjustColumnWidth = True
.TextFilePlatform = 932
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
WS.Names(.Name).Delete
.Delete
|
|