2014-02-13 207 views
1
Dim xl As New Excel.Application 
Dim xlBook As Excel.Workbook = xl.Workbooks.Open(myExcelFileName) 
Dim xlSheet As Excel.Worksheet = xlBook.Sheets("Sheet1") 

所以我有一個打開的Excel文件中的一些操作後執行上面的代碼, 的問題是中小企業表包含空間有例如「sheetx」Excel工作表名稱錯誤

名,並試圖在讀入紙 昏暗xlSheet作爲Excel.Worksheet = xlBook.Sheets( 「工作表Sheet1」)

它捕獲錯誤HRESULT 0x8002000B

回答

0

如果你真的需要,以應付不同的名稱,在不同的指標,那麼它很容易編寫一個函數來找到該表,可以容納名稱的變化,因爲你需要。

例如:

Sub test() 

    Dim sheet As Excel.Worksheet 

    Set sheet = GetSheet("sheet2") 

    sheet.Activate 

End Sub 

'Returns first sheet with a matching name 
Function GetSheet(toFind As String) As Excel.Worksheet 

    'First parse the name to find 
    toFind = ParseName(toFind) 

    'Loop through the sheets collection 
    For Each sheet In ActiveWorkbook.Sheets 

     'Check if the sheet name matches the one we're looking for. 
     If ParseName(sheet.name) = toFind Then 

      'If match then return 
      Set GetSheet = sheet 
      Exit For 

     End If 

    Next sheet 

    'Remember to handle no matches: 
    'Either raise an error or return Nothing depending on your requirements 

End Function 

'Common function for simplifying name for comparison purposes. 
'This version allows for spaces in the name, and differences in Upper/Lower casing. 
Function ParseName(toParse As String) As String 

    toParse = Replace(toParse, " ", "") 
    toParse = UCase(toParse) 

    ParseName = toParse 

End Function 
+0

如果你喜歡我的問題upvote it – MohammadMMohammad

+0

@MohammadMMohammad替換(你的評論,「問題」,「答案」) –

+0

取代什麼? – MohammadMMohammad

0

也許您的Excel版本不會說英語。而「表單」在本地語言中是一個骯髒的詞,它有點用英語;)你的名字暗示英語不是默認語言。使用索引而不是名稱,以避免這樣的意外:

xlWorkSheet = CType(xlWorkBook.Sheets(1), Excel.Worksheet) 

SOURCE

+0

不能使用索引,因爲它不是固定的,我需要通過名稱來獲得工作表... – MohammadMMohammad

+0

如果你喜歡我給予好評疑問的 – MohammadMMohammad

+0

嘿,你這個傢伙 複製的答案 http://stackoverflow.com/questions/14665903/excel-with-vb-net-exception-from-hresult-0x8002000b-disp-e-badindex – MohammadMMohammad