excel 如何在For循环中为每个结果分配一个新变量?

icomxhvb  于 2023-06-25  发布在  其他
关注(0)|答案(4)|浏览(168)

我试图在列(H)中搜索值,如果有值,则返回列C中的值并将其分配给变量。
我想使用For循环来搜索结果(该列大部分是空白的)。在有结果的地方,我想为每个结果创建一个新的变量,以供以后使用。永远不会有超过5个结果。这是我尝试过的方法,但是把变量名放在一起对我不起作用。

Dim xDat1 As String
Dim XDat2 As String
Dim xDat3 As String
Dim xDat4 As String
Dim xDat5 As String

d = 1
For i = 186 To 235
If Not wsElog2.Range("H" & i) Is Nothing Then
    'get result from column C, and assign to a variable (xDat + the d value).
    xDat & d = wsElog2.Range("C" & i).Text
    'the above is showing red error - not sure how to put xDat and d together
End If
d = d + 1
Next i
fbcarpbf

fbcarpbf1#

你的主要问题是线路

If Not wsElog2.Range("H" & i) Is Nothing Then

其中不检查相应单元格是否为空... Is Nothing应该只用于对象,你试着检查一个对象的值(一个Range,它永远不会是Nothing
第二个问题是你不能通过连接来构建变量名...
所以,请测试下一个改编的代码。它将使用一个Scripting.Dictionar来保存你需要的变量:

Sub testUseVariables()
   Dim wsElog2 As Worksheet, i As Long, dict As Object

    Set wsElog2 = ActiveSheet 'please, use the necessary sheet

    Set dict = CreateObject("Scripting.Dictionary")
    For i = 186 To 235
        If wsElog2.Range("H" & i).Value <> "" Then
            dict("H" & i) = wsElog2.Range("C" & i).text 'I used Text only because you wonted that.
                                                        'but, if the cell/column is not AutoFit, it will return only what you can see!
        End If
    Next i
    'you can test the result in the next way:
    If dict.count > 0 Then
        Debug.Print Join(dict.keys, "|")     'just to see where from the it comes (in H:H)
        Debug.Print Join(dict.Items, "|")    'the returned result
        Debug.Print dict.keys()(0), dict.keys()(1) 'a way of returning the item of a specific key number
    End If
End Sub

下一个版本能够模拟构建变量的方式,但现在,作为一个字符串,它可以工作:

Sub testUseVars()
   Dim wsElog2 As Worksheet, d As Long, i As Long, dict As Object
   Const xD As String = "xDat"
   
    Set wsElog2 = ActiveSheet 'please, use the necessary sheet
    
    Set dict = CreateObject("Scripting.Dictionary")
    For i = 186 To 235
        If wsElog2.Range("H" & i).Value <> "" Then
            d = d + 1
            dict(xD & d) = wsElog2.Range("C" & i).text 'I would suggest using Value instead of Text...
        End If
    Next i

    'you can test the result in the next way:
    If dict.count > 0 Then
        Debug.Print Join(dict.keys, "|")     'just to see where from the it comes (in H:H)
        Debug.Print Join(dict.Items, "|")    'the returned result
        Debug.Print dict("xDat1"), dict("xDat2") 'a way of returning the item for a specific key
    End If
End Sub
7lrncoxx

7lrncoxx2#

使用数组代替许多编号变量

    • 快速修复(For...Next)**
Sub Test()
    
    Dim rCount As Long: rCount = 235 - 186 + 1
    
    Dim dArr() As String: ReDim dArr(1 To rCount)
    
    Dim i As Long, dCount As Long
    
    For i = 186 To 235
        If Len(CStr(wsELog2.Range("H" & i).Value)) > 0 Then
            dCount = dCount + 1
            'get result from column C, and assign to a variable (xDat + the dCount value).
            dArr(dCount) = CStr(wsELog2.Range("C" & i).Value)
            'the above is showing red error - not sure how to put xDat and dCount together
        End If
    Next i

    ' Check if all lookup cells were blank.
    If dCount = 0 Then
        MsgBox "All lookup cells were blank.", vbCritical
        Exit Sub
    End If
    
    ' Check if any blanks were found.
    If dCount < rCount Then ' not all lookup cells were not blank
        ReDim Preserve dArr(1 To dCount) ' resize the array
    'Else ' all lookup cells were not blank; do nothing
    End If
    
    ' Continue using the array...
    
    ' Return the comma-separated results in the Immediate window (Ctrl+G).
    Debug.Print Join(dArr, ", ")
    
    Dim d As Long
    
    ' Loop through the results and return one per row
    ' in the Immediate window.
    For d = 1 To dCount
        Debug.Print dArr(d)
    Next d

End Sub
    • 更多详情:完整示例(For Each...Next)**

Sub MatchesToArray()

    ' Reference the workbook and the worksheet.
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    Dim ws As Worksheet: Set ws = wb.Sheets("ELog2") ' adjust!
    
    ' Reference the (same-sized) single-column ranges.
    Dim lrg As Range: Set lrg = ws.Range("H186:H235") ' Lookup Range
    Dim rrg As Range: Set rrg = lrg.EntireRow.Columns("C") ' Return Range
    
    ' Write the number of rows to a variable.
    Dim rCount As Long: rCount = rrg.Rows.Count ' or lrg.Rows.Count
    
    ' Define a 1D one-based array of the same size as there are rows.
    Dim dArr() As Variant: ReDim dArr(1 To rCount)
    
    Dim lCell As Range, r As Long, dCount As Long
    
    ' Loop through the cells of the lookup range.
    For Each lCell In lrg.Cells
        r = r + 1 ' current (lookup/return) row index
        ' Check if the lookup cell is not blank.
        If Len(CStr(lCell.Value)) > 0 Then ' the lookup cell is not blank
            ' Write the value from the current row index of the return range
            ' to the next (current) element of the array.
            dCount = dCount + 1
            dArr(dCount) = rrg.Cells(r).Value
        'Else ' the lookup cell is blank; do nothing
        End If
    Next lCell
    
    ' Check if all lookup cells were blank.
    If dCount = 0 Then
        MsgBox "All lookup cells were blank.", vbCritical
        Exit Sub
    End If
    
    ' Check if any blanks were found.
    If dCount < rCount Then ' not all lookup cells were not blank
        ReDim Preserve dArr(1 To dCount) ' resize the array
    'Else ' all lookup cells were not blank; do nothing
    End If
    
    ' Continue using the array...
    
    ' Return the comma-separated results in the Immediate window (Ctrl+G).
    Debug.Print Join(dArr, ", ")
    
    Dim d As Long
    
    ' Loop through the results and return one per row
    ' in the Immediate window.
    For d = 1 To dCount
        Debug.Print dArr(d)
    Next d

End Sub
    • 结果**
1, 5, 7, 10, 13
 1 
 5 
 7 
 10 
 13
u5i3ibmn

u5i3ibmn3#

简单的答案是,如果你知道不超过5个,就使用一个数组,像这样:

Dim xDats(5) As String
Dim d = 1
For i = 186 To 235
    If Not wsElog2.Range("H" & i) Is Nothing Then
        'get result from column C, and assign to a variable (xDat + the d value).
        xDats(d) = wsElog2.Range("C" & i).Text
        'the above is showing red error - not sure how to put xDat and d together
        d += 1
    End If
Next i

但是,使用List(Of String)可能更好,因为这会给予您的代码稍微更清晰,并且可以在超过5个的情况下消 debugging 误。

Dim xDats As New List(Of String)
For i = 186 To 235
    If Not wsElog2.Range("H" & i) Is Nothing Then
        'get result from column C, and assign to a variable (xDat + the d value).
        xDats.Add(wsElog2.Range("C" & i).Text)
        'the above is showing red error - not sure how to put xDat and d together
    End If
Next i
zvms9eto

zvms9eto4#

你不能以这种方式引用变量,这是有原因的。声明一个数组而不是变量。将数组重新调整为所需的大小,然后使用i变量依次寻址数组中的每个元素。
下面是如何声明数组和调整数组大小的方法

Dim MyArray() As Integer' Declare dynamic array. 
Redim MyArray(5) ' Allocate 5 elements. 
For I = 1 To 5 ' Loop 5 times. 
 MyArray(I) = I ' Initialize array. 
Next I

由于i循环不是从1开始,所以不应该使用i作为数组索引。相反,可以使用d变量,这样就可以

dim ArrayRows as Integer, d as Integer, i as Integer
Dim MyArray() as String
ArrayRows = 235 -186
Redim MyArray(ArrayRows)
d = 1
For i = 186 To 235
  
   ' replace the existing IF condition with a better one
   ' If Not wsElog2.Range("H" & i) Is Nothing Then
   If wsElog2.Range("H" & i).Value <> "" Then
      MyArray(d) = wsElog2.Range("C" & i).Text
   end if
   d = d + 1
next i

相关问题