需要一种方法将电子表格数据粘贴到我的vba表格单元格中?

需要一种方法将电子表格数据粘贴到我的vba表格单元格中?

我有一个csv电子表格,更新了我每天下载的新数据。 我想复制这个csv文件中的所有列,并将其粘贴到我的vba表单的另一个工作簿中相应的文本框中。

例如

说CSV文件有4列,数据,ID,名字,姓氏

我只是复制整个行的4列,并将其粘贴到我的VBAforms到正确的4文本框。

我不想复制和粘贴每个人,因为我有超过4列,我需要一个更快的方式,所以只有一个粘贴将他们粘贴到正确的文本框。 可以这样做吗?

请帮忙。

谢谢

Private Sub TextBox1_Change() Dim splitText splitText = Split(Me.TextBox1.Value, vbTab) If UBound(splitText) > LBound(splitText) Then Me.TextBox1.Value = splitText(LBound(splitText)) Me.TextBox2.Value = splitText(LBound(splitText) + 1) Me.TextBox3.Value = splitText(LBound(splitText) + 2) Me.TextBox4.Value = splitText(LBound(splitText) + 3) End If End Sub 

“现在把你的东西粘贴到第一个单元格中

受德克解决scheme启发,我添加了一些function,使表格dynamic。 这只是为了展示这个概念,它与原始问题有关,特别是处理来自input的dynamic范围的列。 它的不同之处在于,数组会考虑input列的dynamic范围,然后根据数组中的项目数量创build文本框。

这是什么:

  • 命令button复制行(例如:“A”),使用范围的lastColvariables。 你可以绕过这个,因为用户窗体将粘贴剪贴板,不pipe它是什么来源,只要你已经复制了行。
  • 带有1个文本框的用户表单打开
  • 剪贴板内容自动粘贴到Text1中。
  • 创build一个数组,通过TAB分割Text1的值。
  • UserForm重新resize,以适应每个文本框。
  • 对于数组中的每个项目(不包括要分配给Text1的索引(0)),将创build一个新的TextBox并分配数组值。
  • 在closures用户窗体后,每个名称以“Text”开头的TextBox都将被删除,重置表单以备下次使用。

笔记:

  • 使用这种命名方法,文本框将被命名为“Text1” – “Text(n)”
  • 我不包含TextBoxes的标签。
  • 如果您有大量的列/文本框,请在UserForm上设置属性。
    'ScrollBars = 2 fmScrollBarsVertical'

可选:事件从Row1复制数据并启动放置在模块中的UserForm。

 Sub DynamicTextFormLaunch() Dim lastCol As Long lastCol = ActiveSheet.Cells(1, Columns.count).End(xlToLeft).column With ActiveSheet .Range("A1", (.Cells(1, lastCol))).Copy UserFormName.Show 'Set your UserForm name here End With End Sub 

用户窗体代码:下面的所有内容都在用户窗体代码中

 Sub UserForm_Activate() Text1.Paste End Sub 

文本更改事件:

 Sub Text1_Change() Dim csvArray() As String Dim lCount As Long, maxCols As Long Dim tempHeight As String csvArray = Split(Text1.Value, vbTab) maxCols = UBound(csvArray) + 1 Text1.Value = csvArray(0) tempHeight = 55 + (15.5 * maxCols) 'Set new height for 15.5 pixels per TextBox Me.Height = tempHeight For lCount = 2 To maxCols 'Not using 1 for Loop because Text1 was already set. 'Create a new TextBox and assign its size, name, and value. Set ctlTXT = Controls.Add("Forms.TextBox.1", "Text" & lCount) ctlTXT.name = "Text" & lCount ctlTXT.Left = 15 ctlTXT.Height = 15: ctlTXT.Width = 100 ctlTXT.Top = (lCount - 1) * 17 + 2 ctlTXT.Value = csvArray(lCount - 1) 'Set the value of the new TextBox Next lCount End Sub 

closures事件:

 Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer) Call ResetBoxes End Sub 

删除已创build的文本框。

 Private Sub ResetBoxes() Dim ctrl As Control Dim tempName As String Dim tempNum As String For Each ctrl In Me.Controls tempName = Left(ctrl.name, 4) tempNum = Right(ctrl.name, 1) 'Checking to NOT delete Text1 If tempName = "Text" And tempNum <> "1" Then Me.Controls.Remove (ctrl.name) End If Next MsgBox ("Removed new TextBoxes, and reset UserForm to original controls.") End Sub 

之前

例1例题