VBA从我的PERSONAL wb运行是完美的,复制到发行版wb它打破了。为什么呢?

时间:2016-09-28 16:33:11

标签: excel vba excel-vba

我在我的个人书中的宏中有以下代码,它完美无缺。

我试图将其复制到实际运行中,因此我可以将其发送给其他人使用,并且它会在注释行中突破" XXXXXX& #34 ;.所选的wb正在打开,但该书不会进行后续编辑。应该发生在打开的工作簿上的以下所有代码(删除列等)只发生在运行宏的wb上,这是次优的。

我不知道为什么!欢迎任何想法。

谢谢

萨姆

Sub PredictBoxValue()

Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim FldrPicker As FileDialog
Dim TitleName As String
Dim sas As String
Dim sos As String
Dim unusedRow As Long
Dim filename As String

'Optimize Macro Speed
Application.ScreenUpdating = False
'Application.EnableEvents = False
'Application.Calculation = xlCalculationManual

'Retrieve Target Folder Path From User

sos = ActiveWorkbook.Name

ActiveSheet.Range("B11", "AF11").Clear

Dim fNameAndPath As Variant
fNameAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.XLS),              
*.XLS", Title:="Select File To Be Opened")
If fNameAndPath = False Then Exit Sub
Set wb = Workbooks.Open(fNameAndPath)

sas = ActiveWorkbook.Name

'Delete extraneous columns and rows
'XXXXXXXXXXX
TitleName = Cells(5, 2).Value

Columns(8).Delete
Columns(12).Delete
Columns(12).Delete
Columns(3).Delete
Columns(2).Delete
Columns(1).Delete
Rows(3).Delete
Rows(2).Delete
Rows(1).Delete

Here:

Do Until Cells(2, 1).Value = "1"

Range("A1").End(xlDown).Select

'Do Until ActiveCell.Value = "1"
'ActiveCell.Offset(1).Select
'Loop

Do While ActiveCell.Value < 1
ActiveCell.EntireRow.Delete
ActiveCell.Offset(-1, 0).Select

Loop

ActiveCell.Offset(-1, 1).Select

Do While ActiveCell.Offset(0, -1).Value > 30
ActiveCell.EntireRow.Delete
GoTo Here

Loop

ActiveCell.Resize(, 7).Cut ActiveCell.Offset(1, 0).End(xlToRight).Offset(0,     
1)
ActiveCell.EntireRow.Delete

Loop

Rows(1).EntireRow.Delete

Cells(1, 1) = TitleName
Range("A1", Range("A1").End(xlToRight)).Copy

Windows(sos).Activate

ActiveSheet.Cells(11, 2).PasteSpecial (xlPasteValues)

Application.CutCopyMode = False


Windows(sas).Activate

'Save and Close Workbook
 wb.Close SaveChanges:=False

 Windows(sos).Activate

ActiveSheet.Cells(5, 3).Select

'Message Box when tasks are completed
MsgBox ("Data uploaded for ") & Range("B11")


ResetSettings:
  'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True


End Sub

1 个答案:

答案 0 :(得分:1)

我仔细看了一下你的代码。我想你是说你要从macros.xlsm(或类似的东西)运行代码,并让它在mydata.xlsx(或其他类似的)上运行。因此,在您的宏中,ThisWorkbook会引用macros.xlsm(您是否需要参考)。

完成Set wb = Workbooks.Open(fNameAndPath)以打开mydata.xlsx后,在谈论wb时,始终只会引用wb.Sheets("whatever")mydata.xlsx

  • 如果没有工作表参考,请不要使用ColumnsRowsSheetsCells
  • 根本不要使用ActiveWorkbook / ActiveWorksheet
  • 使用命名范围代替ActiveCell,例如this answerthe question BruceWayne noted

应该照顾它!

<soapbox>一般情况下,请注意缩进并使用较长的变量名称 - 这两种方法都可以帮助您避免在处理此代码时出现错误。</soapbox>