使用userform中的文本框来定义variables?

我目前运行一个macros来比较最近的一张数据和之前的报告,并突出显示更改。 它自行工作正常。 但是,现在我们希望能够比较任何时间段的选定表格。 我的想法是用两个文本框popup一个简单的用户表单,用户可以使用它来指定他想要比较哪两个报表。 尽pipe我试图宣布公共variables,但我很失落; 我有atm是:

Option Explicit Public shtNew As String, shtOld As String, _ TextBox1 As TextBox, TextBox2 As TextBox Sub SComparison() Const ID_COL As Integer = 31 'ID is in this column Const NUM_COLS As Integer = 31 'how many columns are being compared? Dim rwNew As Range, rwOld As Range, f As Range Dim X As Integer, Id shtNew = CSManager.TextBox1 shtOld = CSManager.TextBox2 'Row location of the first employee on "CurrentMaster" sheet Set rwNew = shtNew.Rows(5) Do While rwNew.Cells(ID_COL).Value <> "" Id = rwNew.Cells(ID_COL).Value Set f = shtOld.UsedRange.Columns(ID_COL).Find(Id, , xlValues, xlWhole) If Not f Is Nothing Then Set rwOld = f.EntireRow For X = 1 To NUM_COLS If rwNew.Cells(X).Value <> rwOld.Cells(X).Value Then rwNew.Cells(X).Interior.Color = vbYellow rwNew.Cells(33) = "UPDATE" Else rwNew.Cells(X).Interior.ColorIndex = xlNone End If Next X End If Set rwNew = rwNew.Offset(1, 0) 'next row to compare Loop Call SUpdates End Sub 

我的build议是使用combobox代替文本框。 用两个命令button和两个combobox创build一个UserForm_Initialize()使用此代码填充UserForm_Initialize()事件中的combobox。

 Private Sub UserForm_Initialize() Dim ws As Worksheet For Each ws In ActiveWorkbook.Sheets ComboBox1.AddItem ws.Name: ComboBox2.AddItem ws.Name Next End Sub 

然后使用OKbutton中的代码来进行比较。

 Private Sub CommandButton1_Click() Dim shtNew As Worksheet, shtOld As Worksheet If ComboBox1.ListIndex = -1 Then MsgBox "Please select the first sheet" Exit Sub End If If ComboBox2.ListIndex = -1 Then MsgBox "Please select the Second sheet" Exit Sub End If Set shtNew = Sheets(ComboBox1.Value) Set shtOld = Sheets(ComboBox2.Value) '~~> REST OF THE CODE HERE NOW TO WORK WITH THE ABOVE SHEETS End Sub Private Sub CommandButton2_Click() Unload Me End Sub 

HTH

希德

为了一个简单的修复,你不能只是颜色(对不起,我是英文!)你想参考的工作表,然后做一些事情:

 Sub ListSheets() 'lists only non-coloured sheets in immediate window '(could amend to add to combo boxes) Dim w As Worksheet 'loop over worksheets in active workbook For Each w In Worksheets If w.Tab.Color Then 'if tab color is set, print Debug.Print w.Name End If Next w 

让我知道这是否解决了你的问题。