excel 在Textbox1中显示选定的单元格区域

guz6ccqo  于 2022-12-01  发布在  其他
关注(0)|答案(1)|浏览(184)

我在尝试将选定范围的单元格从Excel显示到UserForm文本框时遇到了问题,例如C1:E14.。下面的代码给了我一个Runtime error '13' Type Mismatch

Private Sub CommandButton1_Click()
Dim ActSheet As Worksheet
Dim SelRange As Range
Set ActSheet = ActiveSheet
Set SelRange = Selection
Range("TABLE").Select
Application.Goto "TABLE"
UserForm1.TextBox1.Text = Range("C1:E14").Value
'UserForm1.TextBox1.Text = Range("C1:E14").Select
End Sub

如果我使用.Value,则会出现上述错误,但如果我使用.Select "True",则会在UserForm文本框中打印。

c2e8gylq

c2e8gylq1#

注解是正确的。您正试图将范围设置为字符串。
你可以用这样的方法把它变成一个范围

Public Function Join(seperator As String, rng As Variant) As String

    Dim cell As Variant
    Dim joinedString As String
    For Each cell In rng
        joinedString = joinedString & cell & seperator
    Next cell
    joinedString = Left(joinedString, Len(joinedString) - Len(seperator))
    Join = joinedString

End Function

然后
UserForm1.TextBox1.Text = Join(",",Range("C1:E14"))
或者如果您想在每个单元格中创建新行

Dim joinedString as string
joinedString  = Join("|",Range("C1:E14"))
UserForm1.TextBox1.Text = Replace(joinedString  , "|", vbCrLf)

相关问题