如何使用文本框中的string作为excel vba中的范围的参考?

我是VBAmacros的新手。 我创build了一个用户窗体,通过复制和粘贴Excel内容来节省一些时间。

现在我有以下问题:我从Userform – Textbox(txtHRS_ANW)得到一个string输出。 我创build了与命名范围完全相同的名称。 现在我想使用string输出作为命名范围的参考。 我不能在括号中添加双引号 – 我尝试使用“”“”和字符(34)。

我的代码如下:

Private Sub cmdHRSLoading_Click() Dim NameRange As String If chkANW = True Then NameRange = Me.txtHRS_ANW.Value 'gives me following string HRS_ANW_CORP01 (until CORP10 depending on user entry) Sheet5.Range(NameRange).Select 'here I would like to use the string as a reference for the range Selection.Copy Sheet9.Range("A" & Rows.count).End(xlUp).Offset(1).Select Selection.Paste End If End Sub 

使用以下过程:

 Private Sub cmdHRSLoading_Click() Dim MyNameRange As String If chkANW = True Then MyNameRange = Me.txtHRS_ANW 'gives me following string HRS_ANW_CORP01 (until CORP10 depending on user entry) Application.Goto (MyNameRange) 'here I would like to use the string as a reference for the range Selection.Copy Sheet9.Activate Range("A" & Rows.count).End(xlUp).Offset(1).Select ActiveSheet.Paste End If End Sub 

使用Application.GoTo方法。 你也不需要在Me.txtHRS_ANW之后使用.value

—使用ActiveSheet.PasteSelection.Paste

也可以写成:

 Private Sub cmdHRSLoading_Click() If chkANW Then With Sheet9 With .Cells(.Rows.Count, 1).End(xlUp).Offset(0, 1) .Resize(Range(Me.txtHRS_ANW.Text).Rows.Count, Range(Me.txtHRS_ANW.Text).Columns.Count).Value = Range(Me.txtHRS_ANW.Text).Value End With End With End If End Sub 

无需使用剪贴板。