| 
    
     |  | 2つのcsvファイルを以下のように、1つのExcelファイルの別シートに貼り付けたいのです。 testA.csv→testC.exlのsheet1
 testB.csv→testC.exlのsheet2
 それで、作ってみたのですが、アクティブでないsheetだとエラーが出るみたいなのです(エラーの出るシートをアクティブにすると正常に処理される)
 過去ログにWithを使うといいと書いてあったのですが、どうもうまくいきません。
 何かいい方法があれば教えてください。よろしくお願いします。
 
 testA.csvのデータ
 12    本部    1    本部 10:00    0
 
 testB.csvのデータ
 21    大阪    2    本部 12:00    5
 
 testC.exlのソース
 
 Const csv1 = "A.csv"
 Const csv2 = "B.csv"
 
 Sub Auto_Open()
 Dim fname As String
 Dim fno As Integer
 Dim col(0 To 4) As Variant
 Dim i As Integer
 Dim sts As String
 
 'ファイル名
 fname1 = ActiveWorkbook.Path & "\" & csv1
 fname2 = ActiveWorkbook.Path & "\" & csv2
 
 'testA.csvの処理   <--------ここの処理でSheet1に貼り付けたい
 'CSVファイルの内容を貼り付ける
 fno = FreeFile
 On Error GoTo file_not_found
 Open fname1 For Input As #fno
 On Error GoTo 0
 l = 3
 Do Until EOF(fno)
 '一旦String型で受けてVariant型に入れなおす
 For i = 0 To 4
 Input #fno, sts
 col(i) = sts
 Next
 l = l + 1
 
 With Worksheets("sheet1")
 .Range(Cells(l, 2), Cells(l, 6)).Value = col
 End With
 Loop
 Close #fno
 
 'testB.csvの処理   <--------ここの処理でSheet2に貼り付けたい
 'CSVファイルの内容を貼り付ける
 fno = FreeFile
 On Error GoTo file_not_found
 Open fname2 For Input As #fno
 On Error GoTo 0
 l = 3
 Do Until EOF(fno)
 '一旦String型で受けてVariant型に入れなおす
 For i = 0 To 4
 Input #fno, sts
 col(i) = sts
 Next
 l = l + 1
 With Worksheets("sheet2")
 .Range(Cells(l, 2), Cells(l, 6)).Value = col
 End With
 Loop
 Close #fno
 
 'オートフォーマット
 Cells(4, 2).CurrentRegion.AutoFormat _
 Format:=xlRangeAutoFormatLocalFormat3, _
 Number:=False, _
 Font:=False, _
 Alignment:=False
 
 'CSVファイルを削除する
 Kill fname1
 Kill fname2
 
 Exit Sub
 
 file_not_found:
 MsgBox "CSVファイルが見つかりません", vbCritical + vbOKOnly, "システムエラー"
 
 End Sub
 
 |  |