我有一个包含两个工作表(w1和w2)的工作簿 w1中间有两列, col1看起来像这样:
Sample No.
BB01_1_6 6
BB01_1_6 12
BB01_1_7 6
BB01_1_7 12
BB02_1_9 6
BB02_1_9 12
col2看起来像这样:
Results
8.8
10.1
8.9
6.8
7.9
8.4
我希望workheet2(w2)看起来像这样:
Sample|ID|Serial|Mold6|Mold12
BB01 |1 |6 |8.8 |10.1
BB01 |1 |7 |8.9 |6.8
BB02 |1 |9 |7.9 |8.4
所以我想在一个数组中得到6个样本#,在另一个数组中得到12个样本,另外两个得到结果。
然后我想循环遍历一个数组,只打印所有数组的第一个索引值
这是我到目前为止所做的事情:
Dim rng6 As Range
Dim rng12 As Range
Dim contra As Range
With Sheets("w1")
Set contra = .Range(.Range("J18"), .Range("J18").End(xlDown))
End With
For Each c In contra
If Right(c.Text, 10) = "6" Then
Set rng6 = c
Else
Set rng12 = c
End If
Next
它没有通过循环。
我哪里出错了,最好的办法是什么?我已经提供了我认为合适的信息,但如果您需要更多信息,请告诉我。
答案 0 :(得分:1)
只需对您正在做的事情进行一些快速修改:
首先,请始终使用Option Explicit
。使用VBE自动启用此功能,然后转到工具 - >选项 - >编辑器,然后选中需要变量声明。它会为你节省很多心痛和悲伤。
接下来,您将通过查看最右边的12个字符来检查循环的每个单元格中的字符串。这基本上是字符串中的所有字符。如果您在空格处拆分字符串,则可以轻松查看第二项并检查序列值。
Option Explicit
Sub test()
Dim rng6 As Range
Dim rng12 As Range
Dim contra As Range
With Sheets("Worksheet")
Set contra = .Range(.Range("J18"), .Range("J18").End(xlDown))
End With
Dim c As Variant
For Each c In contra
Dim workingString() As String
workingString = Split(c.Text, " ")
If workingString(1) = "6" Then
Set rng6 = c
Else
Set rng12 = c
End If
Next
End Sub
答案 1 :(得分:1)
我想我可能误会了。如果它们总是与6对,然后是12,你可以做以下吗?
Option Explicit
Sub RearrangeData()
Dim wb As Workbook
Dim wsSource As Worksheet
Dim lastRow As Long
Dim loopRange As Range
Set wb = ThisWorkbook
Set wsSource = wb.Worksheets("Worksheet") 'change to sheet name containing delivery info
With wsSource
lastRow = .Cells(.Rows.Count, "J").End(xlUp).Row 'Change as appropriate
Set loopRange = .Range("J18:J" & lastRow)
End With
Dim currentSample As Long
Dim counter As Long
Dim targetSheet As Worksheet
Set targetSheet = wb.Worksheets("Sheet2")
For currentSample = loopRange.Row To loopRange.Row + loopRange.Rows.Count - 2 Step 2
Dim tempString As String
tempString = wsSource.Cells(currentSample, "J")
counter = counter + 1
targetSheet.Cells(counter, 1) = Left$(tempString, 4)
targetSheet.Cells(counter, 2) = Mid$(tempString, 6, 1)
targetSheet.Cells(counter, 3) = Mid$(tempString, 8, 1)
targetSheet.Cells(counter, 4) = wsSource.Cells(currentSample, 43)
targetSheet.Cells(counter, 5) = wsSource.Cells(currentSample + 1, 43)
Next currentSample
End Sub