Excel VBA偏移复制粘贴

时间:2016-06-09 17:04:25

标签: excel-vba vba excel

希望你做得好。我将通过说我不是程序员来预先说明这一点,我确信我开始的代码比我想象的更多错误。希望你能提供帮助:D。

我有一张Excel工作表,它是从另一个程序生成的,如下所示:

excel sheet

但是,此工作表的大小可能会随着来自其他程序的每个新工作表而改变。 (例如,A下次可以有7个,D可以有9个)并且因为我只需要在给定时间内只需要特定的信息组,因此不能轻易地使用所需的数据表,在本例中为B组和只有D。

我希望创建的内容是将表格作为其生成的内容,并将其转换为如下所示:

result sheet

这是我到目前为止编写的代码,但由于我不知道自己在做什么,因此我遇到了很多问题。任何帮助将不胜感激。

Option Explicit
Sub Numbers()
Dim matchesFound As Integer
Dim row As Integer
Dim c As Integer
Dim copyRow As Integer
Dim copyLocationColumn As Integer

Dim arr(2) As String
arr(0) = "1"
arr(1) = "2"
arr(2) = "3"

Function arrayContainsValue(array, varValue) 
  found = false
  for each  = 0 to array 
    if array(i) = varValue then    
      found = true
      exit for       
  arrayContainsValue = found 
End Function

row = 1
c = 1
copyLocationColumn = 1
copyRow = 1

matchesFound = 0
Do While matchesFound < 3
  if arrayContainsValue(arr, ThisWorkbook.Sheets("Data").Cell(column,row))

    matchesFound = matchesFound + 1
    Do While ThisWorkbook.Sheets("Data").Cell(column, row)
      ThisWorkbook.Sheets("postHere").Cell(copyLocationColumn, copyRow) = _
                       ThisWorkbook.Sheets("postHere").Cell(c + 1, row)
      copyRow = copyRow+1
      row = row + 1
    Loop
  End If
 row = row + 1
Loop

End Sub

1 个答案:

答案 0 :(得分:1)

在评论中有许多逻辑错误需要计算,Excel会自动突出显示它们我会做一个解释它们的摘要:
1.功能不能在中间&#34;中间&#34; sub,完成Sub(从sub获取Function并粘贴,直到它显示end sub。
2.array是一个禁止的名字,尝试另一个变量名称
3.对于每个= 0?到数组?你觉得那是什么意思? For Each必须是某个元素中的元素对于Array中的每个元素,例如For和To是用于在数字中定义的东西(对于counter = 1到15)

Function arrayContainsValue(***array***, varValue)  '2nd problem       
found = false
  for each  = 0 to array  '3rd problem
    if array(i) = varValue then    
      found = true
      exit for       
  arrayContainsValue = found 
End Function

.... 4.你最后错过了一个

if arrayContainsValue(arr, ThisWorkbook.Sheets("Data").Cell(column,row)) 

我没有获得与所述问题相关的编码逻辑(?)