减少VBA中的值

时间:2017-06-30 13:20:03

标签: excel vba excel-vba

我是新来的和VBA,并加入,因为一位朋友告诉我这个社区很有帮助。 我目前在VBA中遇到问题如下:

- 用户从工作表中的列表中选择一个代码" Book Rent&#34 ;; - 此代码保存在单元格D10中,并由另一个工作表中的宏保存"租借"表格中保存了多个数据; - 然后在另一个名为" Books" B栏中有书籍代码,C栏中有书名,D中有书籍数量; - 我想要的是当用户租用书籍时,数量减少1(如果数字现在为零,我不需要验证,所以只有减量就足够了);

我尝试过表格(" Book Rent")。细胞(10," D")=表格("图书")。范​​围(&# 34; D5") - 1但它给了我一个错误。 我现在正在尝试使用for循环,但它也给了我一个错误。 如果有人可以给我一些帮助,或者如果您需要更多信息,我很乐意提供帮助。

这是我的for循环:

Dim Looper As Integer
    For Looper = 5 To Sheets("Livros").Cells(Looper, 2) = Sheets("Form Aluguer").Cells(10, "D")
        Sheets("Livros").Cells(Looper, "D").Select
        Cells(Looper, "D") = Cells(Looper, "D") - 1
    Next Looper

顺便谢谢你。

2 个答案:

答案 0 :(得分:1)

如果你想从X循环到Y(其中X> Y),请使用:

For X = 5 to 0 Step - 1

Next

Step命令告诉它如何递增X,0是我们递增X的时间。请记住For循环需要一些数字作为第二个参数,所以你可以这样做:

For X = 5 to Sheets("Form Aluguer").Cells(10, "D")

但如果Sheets("Form Aluguer").Cells(10, "D")包含数字,则只能执行此操作。

如果您想在Sheets("Livros").Cells(Looper, 2) = Sheets("Form Aluguer").Cells(10, "D")时循环,则需要执行以下操作:

Dim looper as Long
Do While Sheets("Livros").Cells(Looper, 2) = Sheets("Form Aluguer").Cells(10, "D")
    looper = looper -1
Loop

答案 1 :(得分:0)

编辑:

以下是我认为您正在寻找的内容,我在本文的底部留下了原来的答案。但是这段代码更像是我认为你需要的工作版本。根据工作簿的布局,可能需要稍微调整一下。

由于你是VBA新手,我添加的评论比平常多。

希望这有帮助

Sub Decrement()
'Declare a BookCount variable to hold the value of the cell containing the number of books
Dim BookCount As Integer
'Declare a range to hold the range of the Books Quantity column
Dim QuantityRng As Range
'Dim two ranges to use during the loops
Dim RentCell As Range, BookCell As Range
'Declare and set a variable named RentRng to the Rental list and BookRng to the Book list's Code column
Dim RentRng As Range, BookRng As Range
Set RentRng = Worksheets("Renting").Range("A:A")
Set BookRng = Worksheets("Books").Range("B:B")

'For every cell in the Renting list
For Each RentCell In RentRng
'Stop the subroutine when the loop encounters a blank cell
    If RentCell.Value = "" Then
        Exit Sub
    End If
'Check every cell in the Book code list
    For Each BookCell In BookRng
'Exit the loop when encounters a blank cell so can look for the next book in the outer loop
        If BookCell.Value = "" Then
            Exit For
        End If
'Check if the Rental worksheet Code Matches the Books worksheet code, and if so then decrements the field by one
        If RentCell.Value = BookCell.Value Then
            Set QuantityRng = BookCell.Offset(0, 2)
            BookCount = QuantityRng.Value
            BookCount = BookCount - 1
            QuantityRng.Value = BookCount
        End If
    Next BookCell
Next RentCell

End Sub

我不确定我是否理解正确,但我会首先声明一个名为BookCount的变量来保存相关单元格的值。然后你可以使用BookCount = BookCount - 1

你遇到的问题是,当你实际想要修改的范围值时,你试图从一个范围中取出1。

然后您可以将范围的值设置为BookCount

这是一个小例子

Sub Decrement()
Dim BookCount As Integer
BookCount = Range("A1").Value
BookCount = BookCount - 1
Range("A1").Value = BookCount
End Sub