简体   繁体   English

带有单元格值的 VBA 循环

[英]VBA Loop with Cell Values

I am pretty new to vba and I am facing a problem I couldn't find a solution to so far.我对 vba 还很陌生,我面临着一个到目前为止找不到解决方案的问题。 I have two lists of names in the worksheet "Source" that I want to use for a for each loop.我在工作表“源”中有两个名称列表,我想用于每个循环。 How can I address those cells by using the correct Worksheet?如何使用正确的工作表处理这些单元格?

I want to access combo boxes that are named "Box variablename " (eg BoxIAA) and associated text boxes in the form " variablename value" (eg IAAvalue) and check the content of all these objects, deleting the two cells to the right (eg D3:E3 or G5:H5) in the worksheet "Source" if the objects are empty.我想访问名为“Box variablename ”(例如BoxIAA)的组合框和“ variablename value”(例如IAAvalue)形式的关联文本框并检查所有这些对象的内容,删除右侧的两个单元格(例如D3:E3 或 G5:H5) 在工作表“源”中,如果对象为空。

My attempt was:我的尝试是:

Dim rng As Range, cell As Range
Set rng = Range(Sheets("Source").Range("C2:C4"), Sheets("Source").Range("F2:F5"))


For Each cell In rng
    If "Box" & cell.Value <> "" Then

        MsgBox "The value is " & "Box" & Range(cell).Value

    Else If
        'Delete two cells to the right in ws "Source"
    End If  

Next cell

I am aware, that I am not addressing the Cells C2:C4 in the worksheet Source correctly, but I really don't know how to do it properly.我知道,我没有正确处理工作表 Source 中的 Cells C2:C4,但我真的不知道如何正确处理。 How can I access the content of the source cells and address the content / the cells for later use?如何访问源单元格的内容并寻址内容/单元格以供以后使用?

Is this what you are trying ( untested )?这是您正在尝试的(未经测试)吗?

Sub Sample()
    Dim rng As Range
    Dim aCell As Range

    On Error GoTo Whoa '<~~ Need this in case it couldn't find the control

    Set rng = Sheets("Source").Range("C2:C4,F2:F5")

    For Each aCell In rng
        '~~> Use Controls() to work with the control
        With Me.Controls("Box" & aCell.Value)
            If .Value <> "" Then
                MsgBox .Value
            Else
                '~~> Do what you want
                Sheets("Source").Range(aCell.Offset(, 1), _
                                       aCell.Offset(, 2)).Delete shift:=xlLeft
            End If
        End With
    Next aCell

    Exit Sub
Whoa:
    MsgBox Err.Description
End Sub

Instead of If .Value <> "" Then you can also use If .ListIndex <> -1 Then .而不是If .Value <> "" Then你也可以使用If .ListIndex <> -1 Then I am assuming that there are no blank values in the combobox.我假设组合框中没有空白值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM