2017-10-15 72 views
-1

我正在使用Ms Access,並且有一個窗體上有10個複選框和一個按鈕。用戶可以檢查1到10個複選框。每個複選框代表一個字。我需要一個代碼循環到從1到10的所有複選框,並給我一個字符串,以便我可以解析它到一個模塊。將所有複選框轉換爲一個字符串

Private Sub cmdOK_Click() 
Dim str1, str2, str3, str4, str5 As String 
Dim strString As String 

If chB1 = True Then 
str1 = "111 - " 
End If 

If chB2 = True Then 
str2 = "222 - " 
End If 

If chB3 = True Then 
str3 = "333 - " 
End If 

If chB4 = True Then 
str4 = "444 - " 
End If 

If chB5 = True Then 
str5 = "555 - " 
End If 

strString = str1 & str2 & str3 & str4 & str5 & Date 
Debug.Print strString 

End Sub 

我現在有這個權利。我能以另一種方式做到嗎? 有什麼幫助嗎?

預先感謝您。

+0

如果'CheckBox1'被選中,它的價值將是TRUE;。如果它的值是'True',你想要將它的'Caption'連接到你的結果字符串中。繼續使用「CheckBox2」。你堅持哪部分? –

+0

添加代碼。我可以用循環來做到嗎? – YvetteLee

回答

3

讓每個CheckBox控制有其關聯的字符串的地方 - 可能是其Caption,可能是其Tag,不管是誰 - 你需要一種方式來獲得從複選框本身是字符串,如果你想避免硬編碼它。

然後,您可以迭代您的複選框,並使用調整大小的複選框的數量的動態數組,您可以將關聯的字符串存儲在每個數組索引中。

Dim items(), itemCount As Long 
Dim ctrl As MSForms.Control, chkBox As MSForms.CheckBox 

For Each ctrl In Me.Controls 'iterate all form controls 
    If TypeOf ctrl Is MSForms.CheckBox Then 'only care for checkboxes 
     Set chkBox = ctrl ' type cast to the MSForms.CheckBox interface 
     If chkBox.Value Then 'only care for checked checkboxes 
      itemCount = itemCount + 1 
      ReDim Preserve items(1 To itemCount) 
      items(itemCount) = chkBox.Tag 'or whatever you've mapped the strings to 
     End If 
    End If 
Next 

然後你就可以加入你想要使用任何分隔數組元素,與VBA.Strings.Join功能:

Debug.Print Join(items, " - ")