[英]If Next statement does not work after the second time loop in VB
我很困惑為什么這個 if 語句在第二個循環之后不起作用。 我想拿起以“[”開頭的單元格並提取“[]”之間的句子。 提取后,應將句子作為列表放在不同的工作表上。
此代碼僅在InStr(Cells(i, 1), "[") > 0
時第一次工作。 但是,此后該測試失敗。
我哪里錯了?
Public rowCount As Integer
Sub Copy()
Dim startNum As Integer, endNum As Integer
Dim str As String
Dim e As Long
Dim le As Long
Worksheets("DataBase").Activate
rowCount = Cells(Rows.Count, 1).End(xlUp).Row
Dim i As Long
Dim ExtractionStrings As String
Dim arr() As Variant
For i = 4 To rowCount
For e = 1 To rowCount
If InStr(Cells(i, 1), "[") > 0 Then
startNum = InStr(Cells(i, 1), "【")
endNum = InStr(startNum + 1, Cells(i, 1), "]")
If startNum <> 0 And endNum <> 0 Then
startNum = startNum + 1
ExtractionStrings = Mid(Cells(i, 1), startNum, endNum - startNum)
str = ExtractionStrings
Worksheets("Sheet1").Activate
Cells(i, 1) = str
Else: MsgBox ("Error")
End If
End If
Next e
Next i
End Sub
這是因為當第一個匹配發生在循環中時,您正在激活 output 工作表“Worksheets(“Sheet1).Activate”,因此下一次迭代,Instr 評估發生在 output 工作表中。
最好始終為您的工作表設置一個變量,例如:
Dim myWsh
Set myWsh = Workbook("x").sheets(1)
因此,在進一步的代碼中,您可以在不激活工作表的情況下引用工作表中的對象:
myWsh.cells(1,1).value = "my value"
請嘗試以下操作,我已經添加了工作表變量並刪除了內部循環(真的不知道那是什么)
Option Explicit
Public rowCount As Integer
Sub Copy()
Dim databaseWsh As Worksheet: Set databaseWsh = ThisWorkbook.Worksheets("DataBase")
Dim outputWsh As Worksheet: Set outputWsh = ThisWorkbook.Worksheets("Sheet1")
Dim rowCount As Long: rowCount = databaseWsh.Cells(databaseWsh.Rows.Count, 1).End(xlUp).Row
Dim outPutCount As Long: outPutCount = 1
Dim i As Long
For i = 1 To rowCount
Dim startNum As Integer: startNum = 0: Dim endNum As Integer: endNum = 0
If InStr(1, databaseWsh.Cells(i, 1), "[") > 0 Then
startNum = InStr(1, databaseWsh.Cells(i, 1), "[")
endNum = InStr(startNum + 1, databaseWsh.Cells(i, 1), "]")
If startNum <> 0 And endNum <> 0 Then
Dim ExtractionStrings As String
startNum = startNum + 1
ExtractionStrings = Mid(databaseWsh.Cells(i, 1), startNum, endNum - startNum)
outputWsh.Cells(outPutCount, 1) = ExtractionStrings
outPutCount = outPutCount + 1
Else: MsgBox ("Error")
End If
End If
Next i
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.