当循环体中存在True
条件时,我的问题似乎是让我的For循环确认我有IF
ELSE
条件。这就是我写的:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'TEST FIND/SEARCH FEATURES
Dim String2Find As String = txtCPUSerial.Text
Dim ColumnNumber As Integer = 1
'Access the worksheet
Dim xlApp As Excel.Application
xlApp = CreateObject("Excel.Application")
xlApp = GetObject(, "Excel.Application")
Dim xlWB As Excel.Workbook = xlApp.Workbooks.Open("C:\Users\Machine\Desktop\DocDirectory\MyDoc.xls")
Dim xWS As Excel.Worksheet
xWS = xlWB.Worksheets("Sheet1")
'TRY TO LOOP THROUGH THE ROWS..
For x As Integer = 1 To xWS.Rows.Count Step 1
'Check if cell value matches the search string...
If xWS.Cells(x, ColumnNumber).value = String2Find Then
MessageBox.Show("Got it..." & String2Find & " in row " & x)
Else
MessageBox.Show("Item not in the sheet...")
Exit For
End If
Next
End Sub
我尝试在我Else
String2Find <> txtCPUSerial.Text
中写一个直接的陈述,但是语法爆炸,或者我仍然收到的消息对话框表格......“,因此我的For循环的True部分在单步执行时被忽略,并且在获得True
条件时不会返回对话框。
如果我删除了Else
,那么显然代码会相应地循环并返回文本,如果文本框值存在于我的工作表中(我在工作表中写了一个任意值来查找。我没有包括或指明导致这种情况发生?
答案 0 :(得分:1)
似乎更容易向您展示如何找到它而不是解释代码中的所有问题:
Dim xlApp = New Excel.Application ' this starts new Excel Application
Dim xlWB = xlApp.Workbooks.Open("C:\Users\Machine\Desktop\DocDirectory\MyDoc.xls")
Dim xlWS = xlWB.Worksheets("Sheet1")
Dim xlColA = xlWS.Range("A:A") ' Column A
Dim xlCell = xlColA.Find(txtCPUSerial.Text) ' or .Find(txtCPUSerial.Text,,,XlLookAt.xlWhole)
If xlCell Is Nothing Then
MsgBox(txtCPUSerial.Text & " not found")
Else
MsgBox(txtCPUSerial.Text & " found on row " & xlCell.Row)
End If
' don't forget to close the Workbook and Excel Application
xlWB.Close()
xlApp.Quit()
How to: Programmatically Search for Text in Worksheet Ranges
答案 1 :(得分:0)
如果代码的目的是找到所有出现并用其他东西替换,我建议使用查找和替换方法。
示例代码,经过测试和运作:
Range object
它的作用:
Nothing
或FoundCell
,以防它找不到任何内容。将结果存储在FoundCell
变量中。Nothing
变量是否为$('#myInput').keyup(function(e) {
if(e.keyCode == 13){
mySearch();
Check();
}
});
function myInput() {
var empt = document.getElementById("myInput").value;
if (empt == "")
{
mySearch();
return false;
}
else
{
return true;
}
}
function mySearch() {
var input, filter, ul, li, a, i;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("myUl");
li = ul.getElementsByTagName("a");
for (tag = 0; tag < li.length; tag++) {
a = li[tag].getElementsByTagName("p")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
li[tag].style.display = "";
} else {
li[tag].style.display = "none";
}
}
}