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”
当试图阅读表格时 Dim xlSheet As Excel.Worksheet = xlBook.Sheets(“Sheet1”)
它捕获错误HRESULT 0x8002000B
答案 0 :(得分:0)
也许您的Excel版本不会说英语。而“表格”是当地语言中的脏词,它有点英文;)你的名字暗示英语不是默认语言。使用索引而不是名称来避免这样的事故:
xlWorkSheet = CType(xlWorkBook.Sheets(1), Excel.Worksheet)
答案 1 :(得分: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