簡體   English   中英

單擊按鈕時,命令按鈕中的VBA代碼不起作用

[英]VBA code in command button doesn't work on button click

我不了解VBA,我只是出於必要而這樣做,請原諒我。 我通常只是做T-SQL。

我在幫助文章中找到以下代碼,以從Excel工作表獲取數據並將其輸出到txt文件中,該文件將用於通過Scribe運行。 至今;

  1. 我已將“命令”按鈕放在工作表上
  2. 我右鍵單擊以查看代碼
  3. 我將文章中的代碼粘貼到VBA編輯器中,並根據需要修改了部分內容(基本上是文件路徑)

當我從編輯器中運行代碼時,它執行得很好。

當我關閉編輯器並單擊工作表上的按鈕時,它將運行,但是生成的文本文件僅是文本文件中適當數量的空字符串。 就像可以看到單元格中有數據但沒有實際數據的行數。

我錯過了明顯的事情嗎? 我在解決問題的幫助文章中看不到更多內容(對於真正的新手來說,它並不是真正寫的)!

Sub CommandButton1_Click()

Dim FilePath As String
Dim rng As Range
Dim CellData As String
Dim LastCol As Long
Dim LastRow As Long

LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column

LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

Set rng = Worksheets("Discount Template").Range("B3")

FilePath = "\\SERVER2012\IT Dept\AccessSupplyChain\Product Discount Uploads\" & rng.Value & "_" & Format(Now(), "yyyymmdd hhmmss") & ".txt"

Open FilePath For Output As #2

For i = 1 To LastRow

    For j = 1 To LastCol

        If j = LastCol Then
        CellData = CellData + Trim(ActiveCell(i, j).Value)

        Else

        CellData = CellData + Trim(ActiveCell(i, j).Value) + ","

    End If

Next j

Print #2, CellData
CellData = ""

Next i

Close #2
MsgBox ("Done")

End Sub

為了獲得單元格的值,您正在使用ActiveCell(i, j).Value但是在您的代碼中我找不到更新ActiveCell

因此,您一次又一次地使用同一單元格。

相反,您應該編寫: Worksheets("youeSheetName").Cell(i, j).Value

您還應該更改用於將LastRowLastCol用於Worksheets("youeSheetName")ActiveSheet Worksheets("youeSheetName")

希望我能幫上忙。

問題是使用ActiveCell並非必須是A1電池!

所以你想用Cells(i, j)更改ActiveCell(i, j) Cells(i, j)

但我還建議您對代碼進行以下重構:

Option Explicit

Private Sub CommandButton1_Click()
    Dim FilePath As String
    Dim rng As Range
    Dim iRow As Long

    Set rng = Worksheets("Discount Template").Range("B3")

    FilePath = "\\SERVER2012\IT Dept\AccessSupplyChain\Product Discount Uploads\" & rng.Value & "_" & Format(Now(), "yyyymmdd hhmmss") & ".txt"

    Open FilePath For Output As #2
    With UsedRange '<--| reference active sheet used range
        For iRow = 1 To .Rows.Count '<--| loop through its rows
            Print #2, Join(Application.Transpose(Application.Transpose(.Rows(iRow))), ",") '<--| print the whole current row in one shot 
        Next
    End With
    Close #2
    MsgBox ("Done")
End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM