我正在学习从这个网站 vb.net 连接:http://www.siddharthrout.com/2012/09/09/checking-if-a-sheet-exists/
我正在尝试检查工作表是否存在并以布尔值记录结果。
Dim SheetNameToCheck As String = "Sheet1"
Dim xs As Excel.Worksheet
Dim sheet_found As Boolean
'~~> Opens an exisiting Workbook. Change path and filename as applicable
xlWorkBook = xlApp.Workbooks.Open("C:...myExcel2007file.xlsx")
'~~> Display Excel
xlApp.Visible = True
'~~> Loop through the all the sheets in the workbook to find if name matches
For Each xs In xlWorkBook.Sheets
If xs.Name = SheetNameToCheck Then
sheet_found = True
Else
sheet_found = False
End If
Next
If sheet_found = True Then
MessageBox.Show("The sheet " & SheetNameToCheck & " found.")
Else
MessageBox.Show("Not found.")
End If
问题是结果是未找到您检查的任何字符串
错误出现在 For 循环中。首先,循环检查 excel Sheet1 以查看它是否满足字符串以检查哪个是"Sheet1"。变量sheet_found显然是"真"。
但是当它转到下一张工作表时,工作表 2 和工作表 3 结果变为 false,我无法检查工作表是否实际存在于工作簿中。
在 sheet_found = True
下应该是 Else
语句之前的Exit For
行,正如 varocarbas 所建议的那样
感谢varocarbas和patrick的回答。这是有效的代码
Dim SheetNameToCheck As String = "Sheet22"
Dim xs As Excel.Worksheet
Dim sheet_found As Boolean
'~~> Opens an exisiting Workbook. Change path and filename as applicable
xlWorkBook = xlApp.Workbooks.Open("C:...myExcel2007file.xlsx")
'~~> Display Excel
xlApp.Visible = True
'~~> Loop through the all the sheets in the workbook to find if name matches
For Each xs In xlWorkBook.Sheets
If xs.Name = SheetNameToCheck Then
sheet_found = True
Exit For
Else
sheet_found = False
End If
Next
If sheet_found = True Then
MessageBox.Show("The sheet " & SheetNameToCheck & " found.")
Else
MessageBox.Show("Not found.")
End If
为什么首先要打扰那个 else 语句?将其设为默认值为假,并且仅在找到工作表时才将其更改为 true。