如何解决特定列的串联字符串VBA
目标:将字符串“ Z”添加到除标题以外的所有行的选定几列中。仅在选择标头(即数组中定义的标头)上串联。
Dim header As Range
ArrayCheck = Array("CarTime","BusTime","PlaneTime")
LastRow = desWS1.Cells.Find("*",SearchOrder:=xlByRows,SearchDirection:=xlPrevious).Row
lcol = desWS1.Cells(1,Columns.Count).End(xlToLeft).Column
For Each header In desWS1.Range(desWS1.Cells(1,1),desWS1.Cells(1,lcol))
For i = LBound(ArrayCheck) To UBound(ArrayCheck)
If header = ArrayCheck(i) Then
desWS1.Range(desWS1.Cells(2,header.Column),desWS1.Cells(LastRow,header.Column)) & "Z"
End If
Next i
Next
这些列中的所有条目均采用以下格式:yyyy-mm-ddThh:mm:ss
解决方法
@SiddharthRout当前单元格是:2020-09-07T13:08:46,我想要的输出是:2020-09-07T13:08:46Z。是的,是的,这是一个字符串。 – 2分钟前Jak Carty
在下面的代码中,我将采样日期和以文本形式存储的日期。我已经注释了代码,因此您在理解它时应该不会有问题。但是,如果您这样做,则只需回发。
这是您要尝试的吗?
代码:
方式1
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long,lCol As Long
Dim ArrayCheck As Variant
Dim i As Long,j As Long
Dim rng As Range
ArrayCheck = Array("CarTime","BusTime","PlaneTime")
'~~> Set this to the relevant worksheet
Set ws = Sheet1
With ws
'~~> Find last row
lRow = .Cells.Find(What:="*",_
After:=.Range("A1"),_
Lookat:=xlPart,_
LookIn:=xlFormulas,_
SearchOrder:=xlByRows,_
SearchDirection:=xlPrevious,_
MatchCase:=False).Row
'~~> Find last col
lCol = .Cells(1,.Columns.Count).End(xlToLeft).Column
'~~> Loop though the cell in 1st row
For i = 1 To lCol
'~~> Loop through the array
For j = LBound(ArrayCheck) To UBound(ArrayCheck)
'~~> Check if they match
If .Cells(1,i).Value2 = ArrayCheck(j) Then
'~~> Set your range from cell 2 onwards
Set rng = .Range(.Cells(2,i),.Cells(lRow,i))
'~~> Add "Z" to the entire range in ONE GO i.e without looping
'~~> To understand this visit the url below
'https://stackoverflow.com/questions/19985895/convert-an-entire-range-to-uppercase-without-looping-through-all-the-cells
rng.Value = Evaluate("index(Concatenate(" & rng.Address & ",""Z""" & "),)")
End If
Next j
Next i
End With
End Sub
注意:为清楚起见,我没有加入字符串",)")
实际操作
方法2
介绍第二种方式
此代码将写入数组,然后使用它。
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long,j As Long,k As Long
Dim rng As Range
Dim tmpAr As Variant
ArrayCheck = Array("CarTime",i).Value2 = ArrayCheck(j) Then
'~> Set your range
Set rng = .Range(.Cells(2,i))
'~~> Store the value in array
tmpAr = rng.Value2
'~~> Work with array
For k = 1 To UBound(tmpAr)
tmpAr(k,1) = tmpAr(k,1) & "Z"
Next k
'~~> write the array back to worksheet
rng.Resize(UBound(tmpAr),1).Value = tmpAr
End If
Next j
Next i
End With
End Sub
实际操作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。