アプリ版:「スタンプのみでお礼する」機能のリリースについて

いつもお世話になっております。
私はVB2005入門者です。

EXCELで処理を行っております。
処理事態は完了するのですが
下記のコードの後半部の警告がどうやっても潰せないので
修正方法のアドバイスをお願いします。



Dim xlApp As Excel.Application
Dim xlBooks As Excel.Workbooks
Dim xlBook As Excel.Workbook
Dim xlSheets As Excel.Sheets
Dim xlSheet As Excel.Worksheet

' 必要な変数は Try の外で宣言する
Try ' 必要な変数は Try の中でインスタンス化する
xlApp = New Excel.Application()
xlBooks = xlApp.Workbooks
xlBook = xlBooks.Open("C\:hoge0.xls")
xlSheets = xlBook.Worksheets

xlBook.Worksheets(1).Range("F4") = shhoge(0)
xlBook.Worksheets(1).Range("I4") = shhoge(0)
xlBook.Worksheets(1).Range("K4") = shhoge(5)
xlBook.Worksheets(1).Range("M5") = shhoge(0)
xlBook.Worksheets(1).Range("O4") = shhoge(1)
xlBook.Worksheets(1).Range("R4") = shhoge(1)
xlBook.Worksheets(1).Range("U5") = shhoge(1)
xlBook.Worksheets(1).Range("T5") = shhoge(2)
xlBook.Worksheets(1).Range("W5") = shhoge(3)
xlBook.Worksheets(1).Range("X5") = shhoge(4)

' シートのカウントが 1 より大きければシートを削除する
If xlSheets.Count > 1 Then
' Display アラートを消す
xlApp.DisplayAlerts = False

' シートを削除する
xlSheet = DirectCast(xlSheets(2), Excel.Worksheet)
xlSheet.Delete()
End If

' 1000 ミリ秒 (1秒) 待機する
System.Threading.Thread.Sleep(1000)

' Excel ブックを保存する
xlApp.DisplayAlerts = False
xlBook.SaveAs("C:\hoge.xls")

' Microsoft Excel を終了する
xlApp.Quit()
Finally
' 参照したオブジェクトをすべて解放する
If Not xlSheet Is Nothing Then   ←[警告]値が割り当てられる前に使用されています。
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet)
End If

If Not xlSheets Is Nothing Then   ←[警告]値が割り当てられる前に使用されています。
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheets)
End If

If Not xlBook Is Nothing Then   ←[警告]値が割り当てられる前に使用されています。
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBook)
End If

If Not xlBooks Is Nothing Then   ←[警告]値が割り当てられる前に使用されています。
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlBooks)
End If

If Not xlApp Is Nothing Then   ←[警告]値が割り当てられる前に使用されています。
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp)
End If
End Try
Form2.Show()
End Sub

A 回答 (2件)

放っておいても実害はありませんが、



Dim xlBooks As Excel.Workbooks = Nothing

のように、変数定義時に Nothing を入れておけばよいですよ。
    • good
    • 0
この回答へのお礼

Dim xlApp As Excel.Application = Nothing
Dim xlBooks As Excel.Workbooks = Nothing
Dim xlBook As Excel.Workbook = Nothing
Dim xlSheets As Excel.Sheets = Nothing
Dim xlSheet As Excel.Worksheet = Nothing

これでなくなりました!
実害はないのですね。きちんと覚えておきます!
ありがとうございました

お礼日時:2008/08/21 11:38

例えば以下のようなプログラムがあった場合を考えてみてください。



Dim aa As TextBox
Dim bb As Boolean = False

If Not bb Then
aa = New TextBox
aa.Name = "hoge"
End If

MessageBox.Show(aa.Name)

もしbbがtrueだった場合aaはnewされず、aaには値が割り振られる前に使用されることになり、NullReferenceExceptionが発生します。

要はコーディングする上での作法が悪いですよ、という警告です。
解決するにはNo1さんのように初期値を設定する。
または、どのようにプログラムが流れても値が設定されたうえで参照されるようにコードを記述することです。
    • good
    • 0
この回答へのお礼

非常に参考になりました。

最近VBがいっそう楽しくなったので今後とも
よろしくお願いします!(?)

お礼日時:2008/08/21 11:43

お探しのQ&Aが見つからない時は、教えて!gooで質問しましょう!