【问题标题】:Using VBA If then statement to copy and paste data with TextBox.Values使用 VBA If then 语句通过 TextBox.Values 复制和粘贴数据
【发布时间】:2017-06-12 19:00:59
【问题描述】:

我目前面临以下问题:

源数据目前如下:

Value#1        Value#2
10             AA
11             AA
12             AB
13             AD
1231           AA
125            AB
4312           AA
12314          AA

现在用户有多个用户表单文本框,他可以在其中定义各自的值在哪里:

  • Textbox1 = 定义值的开始行
  • Textbox2 = 值#1 的列
  • Textbox3 = 值#2 的列
  • Textbox4 = 值#2 中的条件

现在我想实现以下目标;用户应该指定他的值#1 在哪里(在 TextBox2 中),然后他应该定义可以在其中找到标准的列(TextBox3 中的 Values#2),然后他应该定义应该过滤哪些标准。

因此,如果他选择在 Textbox4 中键入“AB”,则以下内容必须出现在工作表的第一个可用列中:

Value#1        Value#2
12             AB
125            AB

我当前的代码看起来像这样,但我一直在更改它,但没有任何效果(语法错误)。我实际上确定语法的开头还不错(?),但我不知道如何用 vba 表达我希望他们将列中的值复制到另一个列中,如果条件匹配的话。在这里和其他地方有很多示例,但我找不到任何未预定义范围或值的示例。

Dim c as Range

    If OptionButton1.Value = True Then 'also this only happens if the user decides that an Optionbutton is true         
       For Each c In Sheets ("Table") Range (TextBox3.Value & TextBox1.Value + 1 & ":" & TextBox3.Value & lastrow)
             If cell.Value = TextBox4.Value Then
                    Range (TextBox2.Value & TextBox1.Value + 1 & ":" & TextBox2.Value & lastrow) c.copy c.Offset (, 1) 'syntax-error
             End If
        Next

    End If

我对 VBA 和整个编程很陌生,找不到解决方案。

通过一些研究,我很确定解决这个问题的语法有点像“对于每个“x””等,但我从来没有找到用 TextBox 定义范围和值的东西。

【问题讨论】:

  • "...没有什么真正有效的。" ——会发生什么,为什么与你的预期不同?在您的帖子中添加此信息。
  • 非常感谢您的建议。我希望我的编辑信息有所帮助。

标签: vba excel


【解决方案1】:

关于您的代码的几点说明:

首先,您在For Each c In Sheets ("Table")... 行中循环使用C,但下一行您检查的是If cell.Value = TextBox4.Value,而不是If C.Value = TextBox4.Value

其次,如果您想将该单元格复制到下一列以防它等于TextBox4.Value,请使用C.Copy C.Offset(, 1)

试试下面的代码:

Dim Rng As Range
Dim C As Range

If OptionButton1.Value = True Then 'also this only happens if the user decides that an Optionbutton is true

    ' set the range fisrt , See if you are getting the Error on this line -->
    Set Rng = Sheets("Table").Range(TextBox3.Value & TextBox1.Value + 1 & ":" & TextBox3.Value & lastrow)
    For Each C In Rng
        ' for DEBUG ONLY
        Debug.Print C.Value & " | TextBox4 value: " & TextBox4.Value
        If C.Value = TextBox4.Value Then
            MsgBox "There is a match" ' <-- for DEBUG ONLY
            C.Copy C.Offset(, 1)  ' copy the value from the cell into the next column to the right
        End If
    Next C
End If

【讨论】:

  • 感谢您的提示。真的很感激。也感谢您的代码。我已经尝试过了,它没有做任何事情。没有错误消息,工作表上也没有发生任何事情。
  • 我在代码中添加了 2 行代码来帮助你调试,看看你在即时窗口中得到了什么结果
  • 谢谢。我将这两行代码添加到代码中,但仍然没有任何反应。
  • 成功了!我犯了一个愚蠢的错误并对其进行了调整(我的选项按钮实际上是 optionbutton11 而不是 1。抱歉,我之前没有注意到它。非常感谢!还有一种方法可以将值写在另一个下面而不需要任何空格?而且我想将values#1而不是value#2复制到列中,有可能吗?
猜你喜欢
  • 1970-01-01
  • 2018-04-08
  • 2016-01-10
  • 1970-01-01
  • 2017-07-26
  • 2021-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多