【问题标题】:Copy list of values from textbox in UserForm into Excel sheet将用户窗体中文本框中的值列表复制到 Excel 工作表中
【发布时间】:2021-07-13 01:30:32
【问题描述】:

我有一个带有两个文本框(txt11 和 txt12)的用户窗体 (frm10)。 两个文本框都包含一个值列表。

有没有办法可以从底层工作表 (Sheet1) 中的这些框中复制值,以便每个值出现在单独的单元格中? 我需要 txt11 中的所有值出现在工作表的 A 列中,而 txt12 中的所有值都出现在同一张表的 B 列中。

非常感谢您提供的任何帮助,蒂姆。

【问题讨论】:

    标签: vba excel copy-paste userform


    【解决方案1】:

    这取决于您的分隔符,但像下面这样的东西会起作用,稍微整理一下(我没有使用 UserForms 很长时间时间,但方法是一样的),你'我只需要适应这两种情况,改变目的地开始等:

    已编辑,以便您可以设置分隔符

    'If you value list is separated by comma
    Dim x As Integer, y As Integer
    Dim str1 as String, strDelim as String
    Dim sh As Worksheet
    Dim c As Range
    
    str1 = txt11 '(can't recall how you allocate from userform to variable...)
    strDelim = Chr(10) ' chr(10) is new line feed, you may need to test what the 
        ' delimiter is, it could be chr(13) (carriage return)
    
    ' Add trailing comma so captures last value
    If Right(str1, 1) <> strDelim  Then
        str1 = str1 & strDelim 
    End If
    
    ' Set sheet and destination for values to start
    Set sh = Worksheets("Sheet1")
    Set c = sh.Range("A1")
    
    ' Set initial x and y
    x = InStr(str1, strDelim)
    y = 1
    
    ' Check at least 1 comma and that value was entered
    If x = 0 Then
        If Len(str1) > 0 Then
            c.Value = str1
        End If
    End If
    
    ' Loop through commas, paste value in cell and offset destination
    Do Until x = 0
        c.Value = Mid(str1, y, x - y)
        y = x + 1
        x = InStr(y, str1, strDelim)
        Set c = c.Offset(1, 0)
    Loop
    
    Set c = Nothing
    Set sh = Nothing
    

    如果分隔符取决于它们如何进入新行,那么你可以替换它们,所以它们都是一样的

    str1 = Replace(str1,chr(13),chr(10))

    然后使用 chr(10) 作为分隔符

    【讨论】:

    • 非常感谢。我的值没有逗号,它们中的每一个都只出现在文本框中的新行中。
    • 你可能已经自己弄清楚了,但我编辑了上面的内容来处理换行/回车。
    【解决方案2】:

    不知道这是否可行,但是...

    ...假设每个文本框中的值已经被分隔

    Private Sub CommandButton1_Click()
      Me.TextBox1.Copy
      Range("A1").PasteSpecial Paste:=xlPasteAll
      Me.TextBox2.Copy
      Range("B1").PasteSpecial Paste:=xlPasteAll
    

    结束子

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多