在userform中使用文本框来定义变量?

时间:2012-03-22 12:28:50

标签: excel vba excel-vba

我目前运行一个宏来将最新的数据表与之前的报告进行比较并突出显示更改。它本身很好用。但是,现在我们希望能够比较任何时间段的选定工作表。我的想法是弹出一个带有两个文本框的简单用户窗体,用户可以用它来指定他想要比较哪两个报告。虽然想要声明公共变量,但我很遗憾;我得到的是:

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

2 个答案:

答案 0 :(得分:3)

我的建议是使用Comboboxes而不是TextBoxes。使用两个命令按钮和两个组合框创建一个userform,并使用此代码填充UserForm_Initialize()事件中的组合框。

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

然后在OK按钮中使用此代码进行比较。

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

西特

答案 1 :(得分:1)

为了一个简单的解决方法,你不能只是颜色(对不起,我是英文!)你想要引用的工作表,然后做一些像:

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

如果这可以解决您的问题,请告诉我。