2013-03-11 104 views
1

我想從具有4個複選框選項的用戶窗體中傳遞的值並將它們寫入單個並置單元格。Excel VBA-將多個用戶窗體複選框值寫入單個單元格

當我選擇我的窗體像這樣:

enter image description here

我想將其保存到這樣一個單元格:

enter image description here

我試着用以下完成這一代碼(見下文),但它不適用於逗號等,如果只有第二,第三或第四項沒有第一項選擇。我確信有更好的方法,但我無法弄清楚或在網上找到答案。

Private Sub cmdSave_Click() 
    Dim colors As String 

    If chkRed = True Then 
     colors = "Red" 
    Else 
     colors = colors 
    End If 

    If chkBlue = True Then 
     colors = colors & ", Blue" 
    Else 
     colors = colors 
    End If 

    If chkGreen = True Then 
     colors = colors & ", Green" 
    Else 
     colors = colors 
    End If 

    If chkYellow = True Then 
     colors = colors & ", Yellow" 
    Else 
     colors = colors 
    End If 

    With colorsSheet 
     .Cells(ActiveCell.Row, 1).Value = colors 
    End With 

    Unload Me 

End Sub 

回答

4

重命名幀控制frameColours然後可以循環的複選框&建立您的字符串;

Dim chk as Control 
Dim colors as string, delimiter as string 

for Each chk In Me.frameColours.Controls 
    if typeOf chk Is msforms.CheckBox then 
     if (chk.Value) then 
      colors = colors & delimiter & chk.Caption 
      delimiter = "," 
     end if 
    end if 
next 

With colorsSheet 
    .Cells(ActiveCell.Row, 1).Value = colors 
End With 
+0

亞歷克斯,那看起來很棒。非常感謝。我會在這裏嘗試一下,讓你知道它是怎麼回事。我還沒有學會如何這樣做,並知道那裏肯定有更好的辦法。 – ReidC 2013-03-11 17:05:18

+0

工作很好。我必須改變的是爲分隔符添加空格以將其從「,」更改爲「,」 – ReidC 2013-03-11 17:30:28

0

如果你想消除輸出像最初的逗號「藍,綠,黃」,你將不得不改變,增加了這些字符串檢查colors是否爲空的代碼。喜歡的東西:

If chkBlue = true Then 
    If colors = "" Then 
     colors = "Blue" 
    Else 
     colors = colors & ", Blue" 
    End If 
End If 

由於 「紅」 是您添加的第一個顏色,你可以假設colors是空的:

If chkRed = True Then 
     colors = "Red" 
End If 

你不」需要Else ... colors = colors

+0

我喜歡(和upvoted)@Alex K.的解決方案。它使用較少的代碼,並且如果添加顏色,則不需要更改代碼。 – Tim 2013-03-11 16:46:45

+0

蒂姆,你是對的。 Alex有一個很好的解決方案。我也喜歡你的,因爲它修復了我的代碼。很高興有兩種方法來完成我所要做的事情。謝謝。 – ReidC 2013-03-11 17:06:08

1
Private Sub Submit_Click() 

Dim lngIndex As Long, strTemp As String 


For lngIndex = 1 To 16 

'There are 16 check boxex, hence 1 to 16 is given 

If Me.Controls("CheckBox" & lngIndex) Then 
    strTemp = strTemp & Me.Controls("TextBox" & lngIndex).Value & vbLf 

'Returns you the output in a new line within the same cell. 

End If 

Next lngIndex 

Sheets("Sheet1").Range("A1").Value = Left$(strTemp, Len(strTemp) - 1) 

End Sub 
相關問題