Excel工作表名称错误

Dim xl As New Excel.Application Dim xlBook As Excel.Workbook = xl.Workbooks.Open(myExcelFileName) Dim xlSheet As Excel.Worksheet = xlBook.Sheets("Sheet1") 

所以我有上面的代码打开excel文件后来执行一些操作,问题是sme页包含空间中的名称例如“sheetx”

当试图读取表格Dim xlSheet As Excel.Worksheet = xlBook.Sheets(“Sheet1”)

它捕获一个错误HRESULT 0x8002000B

如果你真的需要应付不同的名字,在不同的索引,那么它很容易写一个函数来find工作表,容纳名称的变化,你需要的。

例如:

 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 

也许你的Excel版本不会说英文。 而“表单”是本地语言中的一个脏字,它有点儿是英文的;)你的名字是暗示英语不是默认的语言。 使用索引而不是名字来避免这样的事故:

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

资源