添加到Range.Value方法

时间:2016-07-21 00:39:41

标签: vba excel-vba excel

目前我有一个电子表格可以为我自动化一些concenate函数,但它仅限于5列的数组......

ws.Range(Cells(x, 10), Cells(x, 10)).Value = "" & Source(1) & " " & Source(2) & " " & Source(3) & " " & Source(4) & " " & Source(5) & ""

我已经重写了代码,以便更好,更方便地自动执行此任务,其中包括使用Columns.UsedRange函数填充列表的用户窗体。我想取选择列表框的结果,并添加到上面的代码中。换句话说,如果我选择B到D,我的代码就变成......

ws.Range(Cells(x, v), Cells(x, v)).Value = "" & Source(1) & " " & Source(2) & " " & Source(3) & ""

v是lastcolumn + 1,x是从用户窗体中选择的第一列开始的for循环。

那么,添加和删除一个函数的好方法是什么?

提前致谢,

亚当

2 个答案:

答案 0 :(得分:0)

Cells是范围对象。范围(Cell1,Cell2)返回从Cell1延伸到Cell2的范围。例如:范围(" A1"," A10")与范围相同(" $ A $ 1:$ A $ 10")。如果ws是ActiveSheet,那么ws.Range(Cells(x,10),Cells(x,10))。Value等于Cells(x,10).Value。如果ws不是ActiveSheet,您将收到一个方法'范围'对象' _Worksheet'失败  错误,因为除非另有限定,否则假定Cell为ActiveSheet.Cells。

您不需要将字符串换成空字符串。 "" &安培;来源(1)& " " &安培;来源(2)& " " &安培;来源(3)& ""与Source(1)& " " &安培;来源(2)& " " &安培;源(3)

ws.Range(Cells(x, 10), Cells(x, 10)).Value = "" & Source(1) & " " & Source(2) & " " & Source(3) & " " & Source(4) & " " & Source(5) & ""

编写上述代码的更好方法是:

ws.Cells(x, 10).Value =Source(1) & " " & Source(2) & " " & Source(3) & " " & Source(4) & " " & Source(5)

使用Join(SourceArray,Delemeter)连接一维数组的所有元素。

ws.Cells(x, 10).Value = Join(Source, " ")

澄清你的问题,我会提供更具体的答案。

答案 1 :(得分:0)

我通过加入获得了它。谢谢你的时间。这是我的代码,如果有人想做类似的事情......

模块:

Public wb As Workbook
Public ws As Worksheet
Public LastRow As Integer
Public LastColumn As Integer


Sub Button1_Click()
Set wb = ActiveWorkbook
Set ws = wb.Sheets("Line 6 Winder")
LastRow = ws.UsedRange.Rows.Count
LastColumn = ws.UsedRange.Columns.Count
UserForm1.ListBox_Populate LastRow, LastColumn
UserForm1.Show
End Sub

Sub Conc_Data(StartColStr As String, StartIndex As Integer, EndColStr As String, EndIndex As Integer)
Dim source(1 To 26) As String

ColCount = EndIndex - StartIndex
DataColumn = LastColumn + 2
For x = 1 To LastRow
    Z = 0
    For y = StartIndex To EndIndex
        Z = Z + 1
        source(Z) = ws.Range(Cells(x, y), Cells(x, y)).Value
    Next
    ws.Range(Cells(x, DataColumn), Cells(x, DataColumn)).Value = Join(source, "")
Next
End Sub

形式:

Public Sub ListBox_Populate(s As Integer, e As Integer)
Dim Col_Letter As String
Dim vArr As Variant
    For x = 1 To e
        vArr = Split(Cells(1, x).Address(True, False), "$")
        Col_Letter = vArr(0)
        Me.StartList.AddItem Col_Letter
        Me.EndList.AddItem Col_Letter
    Next
End Sub

Private Sub OkayButton_Click()
Dim StartColStr As String
Dim StartIndex As Integer
Dim EndColStr As String
Dim EndIndex As Integer

StartColStr = Me.StartList.Value
StartIndex = Range(Me.StartList.Value & 1).Column
EndColStr = Me.EndList.Value
EndIndex = Range(Me.EndList.Value & 1).Column
Module1.Conc_Data StartColStr, StartIndex, EndColStr, EndIndex
Unload Me

End Sub

Private Sub UserForm_Click()

End Sub