2014-02-13 204 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