Vba excel: 从存储在具有255个字符的单元格(2,1)中的字符串,我尝试将前50个字符复制到一个单元格中,然后将50到100复制到其他单元格中,将150到200复制到其他单元格
我有一个存储在单元格(2,1)中的字符串,包含255个字符,并希望延伸50个单词,我的意思是将每个50个序列字符分成5个单元格。我使用了下面的代码,但字符不是复制的给定限制,它继续前面的早期限制。你能帮忙吗
ThisWorkbook.Sheets("Sheet2").Cells(2, 1) = Data_comp
Comp_data1 = Left(Data_comp, 50) ' copying 50 characters
Comp_data2 = Mid(Data_comp, 50, 100) ' copying 100 characters
Comp_data3 = Mid(Data_comp, 100, 150) ' copying 150 characters
Comp_data4 = Mid(Data_comp, 150, 200)' copying 200 characters
Comp_data5 = Mid(Data_comp, 200, 250) ' copying 250 characters ThisWorkbook.Sheets("Manual_Checks").Cells(1, 2) = Comp_data1 ThisWorkbook.Sheets("Manual_Checks").Cells(1, 3) = Comp_data2 ThisWorkbook.Sheets("Manual_Checks").Cells(1, 4) = Comp_data3 ThisWorkbook.Sheets("Manual_Checks").Cells(1, 5) = Comp_data4 ThisWorkbook.Sheets("Manual_Checks").Cells(1, 6) = Comp_data5
abc1 = Len(Comp_data1) 'shows 50 characters
abc2 = Len(Comp_data2) ' shows 100 characters
abc3 = Len(Comp_data3) '150 characters
abc4 = Len(Comp_data4) '200 characters
abc5 = Len(Comp_data50 '250 characters
答案 0 :(得分:1)
你几乎做到了,但只需要一点点修正
Mid Function(字符串,开头,长度)
Comp_data2 = Mid(Data_comp, 50, 100)
==> Comp_data2 = Mid(Data_comp, 51, 50)
Comp_data3 = Mid(Data_comp, 100, 150)
==> Comp_data3 = Mid(Data_comp, 101, 50)
Comp_data4 = Mid(Data_comp, 150, 200)
==> Comp_data4 = Mid(Data_comp, 151, 50)
Comp_data5 = Mid(Data_comp, 200, 250)
==> Comp_data5 = Mid(Data_comp, 201, 50)
总体更新代码如下
Dim Data_comp As String
Data_comp = "Some Text"
ThisWorkbook.Sheets("Sheet2").Cells(9, 2) = Data_comp
Comp_data1 = Left(Data_comp, 50)
Comp_data2 = Mid(Data_comp, 51, 50)
Comp_data3 = Mid(Data_comp, 101, 50)
Comp_data4 = Mid(Data_comp, 151, 50)
Comp_data5 = Mid(Data_comp, 201, 50)
ThisWorkbook.Sheets("Manual_Checks").Cells(1, 2) = Comp_data1
ThisWorkbook.Sheets("Manual_Checks").Cells(1, 3) = Comp_data2
ThisWorkbook.Sheets("Manual_Checks").Cells(1, 4) = Comp_data3
ThisWorkbook.Sheets("Manual_Checks").Cells(1, 5) = Comp_data4
ThisWorkbook.Sheets("Manual_Checks").Cells(1, 6) = Comp_data5
abc1 = Len(Comp_data1)
abc2 = Len(Comp_data2)
abc3 = Len(Comp_data3)
abc4 = Len(Comp_data4)
abc5 = Len(Comp_data50
答案 1 :(得分:1)
让我整理并简化 Raju 的答案,他们有一个好主意。我将删除Dim for Data_comp,因为它没有显示在问题中。
Dim arrData(4) as String, abc(4) as Integer
ThisWorkbook.Sheets("Sheet2").Cells(2, 1) = Data_comp
For intI = 0 to 4
arrData(intI) = Mid(Data_comp, iniI * 50 + 1, 50)
abc(intI) = Len(arrData(intI))
ThisWorkbook.Sheets("Manual_Checks").Cells(1, 2 + intI) = arrData(intI)
Next
For循环提取每个50个字符的块,将它们分配给一个字符串数组,然后分配给目标单元格,然后从String数组中获取长度以验证长度。
intI * 50 + 1
将在{1,51,101,151,201}
开始中间
2 + intI
将定位单元格列{2,3,4,5,6}
。