2015-05-20 14 views
0

我需要一個宏來查找一行中的字符串(該字符串來自數組),然後在查找該字符串所在的單元格後,將其旁邊的值存儲到另一個數組中。有沒有辦法做到這一點,或者我在想不可能的事情?這是我到目前爲止如何在一行中搜索一個字符串並用它們創建一個數組VBA

Sub ListWorkSheetNames() 
Dim Cellnames(1000) As String 
Dim Shrinkage(1000) As Double 
For i = 1 To Application.Sheets.Count 
Cellnames(i) = Application.Sheets(i).Name 

strName = Cellnames(i) 

Shrinkage(i) = Workbooks(strProjectedRevenue).Worksheet("Month").Rows(2).Find(What:=strName, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False) 

Workbooks(strB.xlsm).Worksheets("Sheet1").Range("E" & i) = Shrinkage 
Workbooks(strB.xlsm).Worksheets("Sheet1").Range("D" & i) = strName 

Next i 
End Sub 
+0

你是什麼意思字符串是來自連續的箭頭?你是說單元格包含數組?或者單元格中的值來自VBA陣列之前? – Sam

回答

0

你不需要兩個我看到的數組。

這是你正在嘗試的(UNTESTED)?我已經評論了代碼。如果您有任何問題,請告訴我。

Sub Sample() 
    Dim ws As Worksheet, wsI As Worksheet 
    Dim MyAr As Variant 
    Dim SearchString As String, tmpString As String, sDelim As String 
    Dim aCell As Range 

    '~~> Worksheet where you need to search 
    Set wsI = Workbooks(strProjectedRevenue).Worksheet("Month") 

    '~~> I am assuming that none of the sheets have this name. Else Change it 
    '~~> to something unique 
    sDelim = "lbochitt" 

    '~~> Loop through the worksheets 
    For Each ws In ThisWorkbook.Sheets 
     '~~> Search String 
     SearchString = ws.Name 

     '~~> Find the string 
     Set aCell = wsI.Rows(2).Find(What:=SearchString, LookIn:=xlValues, _ 
        LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _ 
        MatchCase:=False, SearchFormat:=False) 

     '~~> Check if the result returned anything 
     If Not aCell Is Nothing Then 
      '~~> Store the offset value in a string separated with a delimiter 
      If tmpString = "" Then 
       tmpString = aCell.Offset(, 1).Value 
      Else 
       tmpString = tmpString & sDelim & aCell.Offset(, 1).Value 
      End If 
      Set aCell = Nothing 
     Next 
    Next 

    If tmpString <> "" Then 
     '~~> here is your final array 
     MyAr = Split(tmpString, sDelim) 
    End If 
End Sub 
相關問題