2016-12-30 60 views
0

我試圖編寫一個代碼來完成以下工作 - 從表單「Empl CP」合併E,F和G列中的數據(表示僱員的最後,第一和中間名稱)並將該組合字段寫入「Empl QC」表中。 第一個,最後一個和中間名必須是空格。Do While循環VBA代碼問題中的引用和空格

這個代碼應該在工作表「Empl CP」(Do while循環用於此)中爲每個員工重複。

使用此代碼IM是以下幾點:

Sub CreateEmployees() 

Dim counter As Integer 
Dim cellCount As Integer 

Dim Comb As String 

Sheets("Empl CP").Activate 

cellCount = Application.WorksheetFunction.CountA(Range("A2:A20000")) 'cell count counts number of Employee IDs 
counter = 2 'Counter set on 2 to skip first header row of data 


Do While counter <= (cellCount + 1) ' +1 because counter begins with 2 (ends 1 before cellCount) 

Sheets("Empl CP").Activate 

Comb = "='Empl CP'!E" & counter & "&'Empl CP'!F" & counter & "&'Empl CP'!G" & counter 'COMB filed containing Empl first, last and mid name 

Sheets("Empl QC").Activate 

Worksheets("Empl QC").Range("A" & counter) = Comb 

counter = counter + 1 

Loop 

End Sub 

在上面的代碼,創建「梳狀」參數時,有第一,最後和中間名(之間沒有空格至今代碼工作正確)。如果我嘗試通過輸入"" "" &來增加空格(在「Comb =」行中的計數器之後),我得到一個錯誤,要求我結束語句。在我使用" "" "" " &的情況下,我得到了應用程序運行時錯誤1004(應用程序定義或對象定義的錯誤)。

你能幫我解決這個問題嗎?

+0

請問您可以編輯問題或發表評論,包括額外的空格? 'Comb =「='Empl CP'!E」&counter&「&'Empl CP'!F」&counter&「&'Empl CP'!G」&counter' – Nulled

回答

0

Comb表達應該寫成如下:

Comb = "='Empl CP'!E" & counter & "&"" "" & 'Empl CP'!F" & counter & "&"" "" & 'Empl CP'!G" & counter 

但你最好避免Activate與完全合格的範圍內引用

Join()去功能可幫助這裏

爲如下:

Option Explicit 

Sub CreateEmployees() 
    Dim iDatum As Long 

    With Sheets("Empl CP") 
     With .Range("A2", .Cells(.Rows.count, 1).End(xlUp)) 
      ReDim data(1 To .count) As String 
      For iDatum = 1 To .count 
       data(iDatum) = Join(Application.Transpose(Application.Transpose(.Offset(iDatum - 1, 4).Resize(1, 3).Value))) 
      Next 
     End With 
     Worksheets("Empl QC").Range("A2").Resize(UBound(data)).Value = Application.Transpose(data) 
    End With 
End Sub 
+0

非常感謝您解決我的問題問題。我很感激:) – Ivica

+0

不客氣。良好的編碼! – user3598756