[英]Reading the next line when executing the loop
我創建了VBA代碼以計算單元格內字符的值,然后將其顯示在Msgbox上。
為了使其動態,我插入了一個循環以讀取整行,直到單元格為空。 循環將運行確切的次數,但是不會讀取下一行。
Public Sub Rs()
Dim Text As String
Dim NumChar As String
Dim i As Integer
Dim NumRows As Long
Dim msg1 As String
Application.ScreenUpdating = False
'Get Cell Value
'Get Char Length
Text = Range("B2" & i).Value
NumRows = Range("B2", Range("B2").End(xlDown)).Rows.Count
Range("B2").Select
For i = 1 To NumRows
Text = Range("B" & i).Value
NumChar = Len(Text)
'Character length validation
If Len(Text) >= 15 Then
msg1 = msg1 & Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and Exceeded allowable number of characters!" & vbLf
Else
msg1 = msg1 & Chr(149) & " SVC_DESC " & Text & " has " & NumChar & " characters " & " and it's Valid !" & vbLf
End If
Next i
Application.ScreenUpdating = True
MsgBox msg1
End Sub
如果希望在消息中使用它,則在循環內移動Text = Range("B2").Value
並迭代從中獲取其值的單元格。
Option Explicit
Public Sub Rs()
Dim txt As String, msg1 As String
Dim numRows As Long, numChar As Long, i As Long
Application.ScreenUpdating = False
numRows = Cells(Rows.Count, "B").End(xlUp).Row
For i = 2 To numRows
txt = Cells(i, "B").Value2
numChar = Len(txt)
'Character length validation
If numChar >= 15 Then
msg1 = msg1 & Chr(149) & " SVC_DESC " & txt & " has " & numChar & " characters " & " and it's Valid !" & vbLf
Else
msg1 = msg1 & Chr(149) & " SVC_DESC " & txt & " has " & numChar & " characters " & " and Exceeded allowable number of characters!" & vbLf
End If
Next i
Application.ScreenUpdating = True
MsgBox msg1
End Sub
正如我在下面的評論中所提到的,如果numchar小於15,則msg為“超出了允許的字符數”? 這似乎違反直覺。 您可以將條件更改為If numChar < 15 Then
或交換兩個消息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.