ちょっと試しに。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 |
Sub MainRoutine(TargetName, BaseYear, RoutineType) ExecuteResult = False If RoutineType = "COMPARE_YEAR" Then QueryString = "select * from xxx" ExecuteResult = DbExecute(QueryString, TargetName, BaseYear, RoutineType) End If Call TmporaryDelete If True = ExecuteResult Then MsgBox "完了しました" Else MsgBox "エラーが発生しています" End If End Sub Function DbExecute(QueryString, TargetName, BaseYear, RoutineType) On Error GoTo e Set cn = CreateObject("ADODB.Connection") Set rs = CreateObject("ADODB.Recordset") DbPath = "C:\xxx.accdb" ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" & DbPath & "; Jet OLEDB:Database Password=xxx" cn.Open ConnectionString rs.Open QueryString, cn If RoutineType = "COMPARE_YEAR" Then If False = CompareYear(rs, TargetName, BaseYear, RoutineType) Then GoTo e End If If rs.State = 1 Then rs.Close Set rs = Nothing If cn.State = 1 Then cn.Close Set cn = Nothing DbExecute = True Exit Function e: If rs.State = 1 Then rs.Close Set rs = Nothing If cn.State = 1 Then cn.Close Set cn = Nothing DbExecute = False End Function Function CompareYear(ByVal rs, TargetName, BaseYear, RoutineType) On Error GoTo e Call TmporaryDelete Set w = Sheets.Add: w.Name = "tmp" SheetName = "年度比較(" & BaseYear - 1 & "-" & BaseYear & ")_" & TargetName If True = ExistSheet(SheetName) Then MsgBox "シート名が重複しています" GoTo e End If Sheets("(雛形)年度比較").Copy After:=Sheets(Sheets.Count) ActiveSheet.Name = SheetName 'ActiveSheet.Cells(1, 1).CopyFromRecordset rs CompareYear = True Exit Function e: CompareYear = False End Function Function ExistSheet(SheetName) For Each w In Sheets If w.Name = SheetName Then ExistSheet = True Exit Function End If Next ExistSheet = False End Function Sub TmporaryDelete() Application.DisplayAlerts = False For Each w In Sheets If w.Name = "tmp" Then Sheets("tmp").Delete Next Application.DisplayAlerts = True End Sub |