我从这个站点学到了很好的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显然是“True”。
但是当它转到下一张工作表时,Sheet 2和Sheet3结果变为false,我无法检查工作簿中是否存在工作表。
答案 0 :(得分:1)
sheet_found = True
下的应该是Exit For
语句之前的Else
行,因为varocarbas建议
答案 1 :(得分:0)
感谢varocarbas和帕特里克的答案。这是有效的代码
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
答案 2 :(得分:0)
为什么要在第一时间使用其他声明呢?默认情况下将其设为false,如果找到工作表,则仅将其更改为true。